Comparison of Ajax sending get request and post request

Review the questions encountered when writing code before

Table of contents

code example

Use Ajax to send a get request case:

Use Ajax to send a post request case:

Why do you need to set response headers for post requests in Ajax but not for get requests

For post requests:

However, corresponding to the get request:

In Ajax, set the response header for the post request, the underlying implementation principle;

Why don't we manually set the response header for the get request method in AJAX

Request format and code case of AJAX post request

Use Ajax to make a login verification project

What is the event in the third line of the above js code, and what does the event.preventDefault() method do?

Is the event event object a built-in object?




code example

Use Ajax to send a get request case:

//1.创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//使用xhr对象调用回调函数
xhr.onreadystatechange=function (){
if (this.readyState == 4) {
        if (this.status == 200) {
            document.getElementById("div1").innerText=this.responseText
        }else{
            alert(this.status)
        }    
    }
}
let value = document.getElementById("ipt1").value;
//打开通道
xhr.open("get","/ajax/ajaxrequest1?value="+value,true)
//发送数据
xhr.send()

Use Ajax to send a post request case:

//1.创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//使用xhr调用回调函数
xhr.onreadystatechange=function (){
    if (this.readyState == 4) {
        if (this.status == 200) {
            document.getElementById("div2").innerText=this.responseText
        }else{
            alert(this.status)
        }
    }
}
//打开通道
xhr.open("post","/ajax/ajaxrequest1",true)
//为post请求添加响应头信息
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
let value1 = document.getElementById("ipt1").value;
//发送数据
xhr.send("username="+value1)

Obviously, when sending a post request, we added request header information to it; why is this happening?

Why do you need to set response headers for post requests in Ajax but not for get requests

        In Ajax, both POST requests and GET requests need to set response headers. Regardless of whether the request method is POST or GET, the server needs to set Content-Type and other related header information in the response header to inform the client of the returned data type and encoding method. However, since POST requests usually transmit more data, it is necessary to pay more attention to the settings of request headers and response headers when processing POST requests.

For post requests:

        In Ajax, the main difference between POST and GET requests is the way data is passed. GET requests send data through the URL, while POST requests transmit data in the request body. Since the POST request needs to transmit data in the request body, it is necessary to set the response header to inform the server of the corresponding data format and encoding type.

        Setting response headers ensures that the server can correctly parse the data in the request body and that the client can correctly process the response from the server. There is no request body in the GET request, so there is no need to set the response header.

        In addition, when using POST requests in Ajax, you need to pay attention to some security issues, such as cross-site scripting (XSS) and cross-site request forgery (CSRF). Therefore, when using POST requests, you must ensure that both the request and response headers are set correctly, and that data is properly encrypted and authenticated during transmission.

However, corresponding to the get request:

        In fact whenever Ajax sends a GET request, the browser automatically sets the response headers for that request. After receiving the response from the server, the browser will judge the type of the response content according to the Content-Type field in the response header, and parse it into the corresponding data format.

        Because the data of a GET request is usually contained in the URL rather than transmitted in the request body, there is no need to set response header information such as Content-Type and Content-Length on the server side. The browser can judge the type of the response content according to the Content-Type field in the response header, and automatically parse and process it.

        Although it is not necessary to set the response header information in the GET request, in some cases, it may be necessary to set other response headers, such as Cache-Control and Expires, so that the browser can cache the response result and optimize performance. But these settings are not mandatory, but should be set according to actual needs.

In Ajax, set the response header for the post request, the underlying implementation principle;

        In Ajax, both POST requests and GET requests need to set response headers. Regardless of whether the request method is POST or GET, the server needs to set Content-Type and other related header information in the response header to inform the client of the returned data type and encoding method.

        From the perspective of the underlying implementation principle, when sending a POST request in Ajax, an XMLHttpRequest object will be created and a request will be made to the server. When the server receives the request, it will judge the type of the request body according to the Content-Type field in the request header. If the Content-Type is set to application/x-www-form-urlencoded, it means that the request data is in the form of URL-encoded key-value pairs. At this time, the server will parse the request body into the form of key-value pairs and process the request. If the Content-Type is set to application/json, it means that the request data is submitted in JSON format, and the server will parse the JSON data and perform corresponding processing.

        Since POST requests usually transmit more data, it is necessary to pay more attention to the settings of request headers and response headers when processing POST requests to ensure that data can be transmitted and parsed correctly. Therefore, whether it is a POST request or a GET request, it is necessary to set the response header to ensure that the data can be transmitted and parsed correctly.

Why don't we manually set the response header for the get request method in AJAX

        In AJAX, the GET request method does not need to manually set the response header. When the browser initiates an AJAX GET request, the browser will automatically set some default request headers for the request, including Accept, Accept-Encoding, Accept-Language, etc., and the server will judge what the browser can do based on these request headers. Accept the data format and encoding method, and return the corresponding content. Therefore, we usually don't need to manually set the response header when using AJAX GET request.

        However, if we need to specify some specific response headers, such as setting the Content-Type of the response result, it can also be achieved by setting the HTTP response header on the server side. At this time, whether it is a GET request or a POST request, the corresponding response header information needs to be set on the server side.

Request format and code case of AJAX post request

        AJAX is a technique for updating parts of a web page without refreshing the entire page. A POST request can send data to the server and receive a response. The request format of an AJAX POST request usually includes two parts: header and data.

Request header:

  • Content-Type: Specify the format of the request data, usually application/json or application/x-www-form-urlencoded.

  • X-Requested-With: XMLHttpRequest, indicating that this is an AJAX request.

Request data:

Data can be plain text, JSON format or form data.

The following is a code example of an AJAX POST request, sending a username and password to the server, and receiving a response:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.open("POST", "/login", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
var data = JSON.stringify({"username": "Alice", "password": "123"});
xhttp.send(data);

This code sends a request to the server's /login endpoint, sending data to the server in JSON format. When a response is available, the function will print the response text. Note that in the open() method, the third parameter is set to true, indicating that the AJAX request is asynchronous.

Can the following code be missing in the Ajax post request: xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");

        It is not necessary to set the request header X-Requested-Withas XMLHttpRequest, but this request header is usually used to identify AJAX requests. If the request header is not set, the server may not be able to determine whether the request is an AJAX request, thus affecting the processing method. Therefore, it is recommended to add this request header to the AJAX POST request to ensure that the server can process the request correctly.

Use Ajax to make a login verification project

        A basic login verification project can use AJAX to send a POST request, send the user name and password to the server for verification, and then decide whether to allow the user to log in based on the server response.

The following is a code sample for a simple login validation item:

HTML file:

<!DOCTYPE html>
<html>
<head>
	<title>Login</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script src="login.js"></script>
</head>
<body>
	<form id="loginForm">
		<label for="username">Username:</label>
		<input type="text" id="username" name="username"><br><br>
		<label for="password">Password:</label>
		<input type="password" id="password" name="password"><br><br>
		<input type="submit" value="Login">
	</form>
	<div id="message"></div>
</body>
</html>

        This HTML file contains a form where the user enters a username and password. When the user submits the form, an AJAX request in the JavaScript file is triggered.

JavaScript file:

$(document).ready(function() {
  $('#loginForm').submit(function(event) {
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
      type: 'POST',
      url: '/login',
      data: {username: username, password: password},
      success: function(response) {
        if (response === 'success') {
          $('#message').text('Login successful.');
        } else {
          $('#message').text('Invalid username or password.');
        }
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  });
});

        This JavaScript file contains an event listener that will trigger an AJAX POST request when the user submits the form. The requested data is the username and password and is sent to the server's /login endpoint. If the response is "success", display a successful login message; otherwise, display an invalid username or password message.

        On the server side, any backend language can be used to process POST requests and validate user credentials. If the verification is passed, you can send a "success" response to the client, otherwise send other error messages.

What is the event in the third line of the above js code, and what does the event.preventDefault() method do?

In the above JavaScript code, the third line eventis an event object, which represents the event triggered when the form is submitted.

event.preventDefault()The function of the method is to prevent the browser from performing the default form submission behavior. Since we use Ajax to send form data for

Asynchronous submission, so you need to prevent the default form submission behavior, so as to avoid page refresh and jump.

Is the event event object a built-in object?

        Yes, the event object is a built-in object of the browser, which is automatically created when an event is triggered and passed to the event handler, and contains information related to the event, such as event type, trigger element, mouse position, etc. Different event types create different types of event objects. In JavaScript, we can access the event object through the parameters of the event handler function. For example:

document.getElementById("myButton").addEventListener("click", function(event){
  // 在这里访问事件对象
  console.log(event.type);           // 输出 "click"
  console.log(event.target.id);      // 输出 "myButton"
});

Guess you like

Origin blog.csdn.net/m0_64231944/article/details/130784802