Ajax Basic Knowledge Detailed Explanation
- 2021-07-21 07:23:34
- OfStack
The main function of Ajax is to realize asynchronous access to the server by the browser: send out a small part of data through the XMLHttpRequest object of the browser, interact with the server, and the server returns a small part of data, and then update some pages of the client.
1. Instantiate the XMLHttpRequest object first
var request;
if (window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else{
request=new ActiveXObject("Microsoft.XMLHTTP");
// Compatible ie5 6
}
2. XMLHttpRequest's method sends the request to the server
request.open("POST",get.php,true);// Request
// Settings http To tell the server that we want to use the header information of send Send by key-value pair 1 A form,
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//POST You must set Content-Type The value of is in the open And send Between
request.send("name= Wang 2 Dog &sex= Male ");// Use send Method is submitted to the server
3. Method to get the response
responseText Get response data in string form
responseXML Obtain XML Response data in the form of
status And statusText Returns as numbers and text HTTP Status code
getAllResponseHeader() Get all response headers
getResponseHeader() The value of a field in the query response
4. It is important to listen for changes in readyState properties
The request with 0 was not initialized, and open has not been called yet
Server connection has been established for 1, and open has been called
The request for 2 has been received, and the header information has been received
In the processing of the request for 3, the response body was received
For 4, the request is complete, and the response is ready, and the response is complete
//readyState Triggered when changing
// Pass onreadystatechange Event judgment readyState Changes in attributes
request.onreadystatechange=function(){
if(request.readyState===4&&request.status===200){
// Do 1 Something For example, getting response data request.responseText
}
}
5. Complete XHR
var request=new XMLHttpRequest();//1. Create XHR Object
request.open("GET","get.php?number=" + Data to be submitted in the form ,true);//2. Call open Method
// If it is here, post Request. send Is that 1 Objects containing data
request.send();// Send 1 Some data
request.onreadystatechange=function(){ //3. Monitor and judge whether the server responds correctly
if(request.readyState===4&&request.status===200){
//4. Do 1 Something For example, get the server response content request.responseText
}
}