How Ajax works
Ajax is equivalent to the agent that the browser sends requests and receives responses to partially update page data without affecting the user's browsing of the page, thus improving the user experience.
Ajax implementation steps
- Create Ajax object
var xhr = new XMLHttpRequest();
- Tell Ajax the request address and request method
xhr.open('get', 'http://www.example.com');
- send request
xhr.send();
- Get the response data given by the server to the client
xhr.onload = function () {
console.log(xhr.responseText);
}
Server-side response data format
In real projects, the server-side will use JSON objects as the response data format in most cases. When the client gets the response data, it needs to splice the JSON data and HTML string, and then display the spliced result on the page.
In the process of http request and response, whether it is request parameters or response content, if it is an object type, it will eventually be converted into an object string for transmission.
JSON.parse() // 将 json 字符串转换为json对象
Request parameter passing
1.GET request method
xhr.open('get', 'http://www.example.com?name=zhangsan&age=20');
2.POST request method
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('name=zhangsan&age=20');
Format of request parameters
- application/x-www-form-urlencoded
name=zhangsan&age=20&sex=男
- application/json
{
name: 'zhangsan', age: '20', sex: '男'}
Specify the value of the Content-Type attribute in the request header to be application/json, telling the server that the format of the current request parameter is json.
JSON.stringify() // 将json对象转换为json字符串
Note: The get request cannot submit the json object data format, and the form submission of traditional websites does not support the json object data format.