AJAX
core (
xmlhttprequest
)
AJAX, in fact, adds an extra object to Javascript: Thexmlhttprequest object. All asynchronous interactions are done using the Xmlhttpservlet object. In other words, we just need to learn a new Javascript object.
| 1 |
varxmlHttp = newXMLHttpRequest();(大多数浏览器都支持DOM2规范) |
Note that the support for XMLHttpRequest is different for each browser! in order to handle browser compatibility issues, the following method is given to create the XMLHttpRequest object:
functioncreatexmlhttprequest () {varxmlHttp; //applies to most browsers, as well as IE7 and IE later versions Try{xmlHttp=NewXMLHttpRequest (); } Catch(e) {//Suitable for IE6 Try{xmlHttp=NewActiveXObject ("Msxml2.xmlhttp"); } Catch(e) {//for IE5.5, and earlier versions of IE Try{xmlHttp=NewActiveXObject ("Microsoft.XMLHTTP"); } Catch(e) {}}} returnxmlHttp; }Use process
Step 1: Open the connection to the server (open
method)
When you get the XMLHttpRequest object, you can call the open () method of the object to turn on the connection to the server. The parameters of the open () method are as follows:
Open (method, URL, async):
- method: Request method, usually get< Span class= "S4" or post
Li class= "li5" > url: Requested server address, for example: /ajaxdemo1/ Aservletget request, you can also url
- < Span class= "S3" >async: This parameter can not be given, the default value is true
| 12 |
varxmlHttp = createXMLHttpRequest();xmlHttp.open("GET", "/ajax_get/?a=1", true); |
Step 2: Send the request
When the connection is opened using open , you can call the Send () method of the XMLHttpRequest object to make the request. The parameter of the Send () method is the post request parameter, which corresponds to the request body content of the HTTP protocol and, if the GET request, the connection parameters after the URL.
Note: If there are no parameters, you need to give null as the parameter! If you do not give null as a parameter, it may cause FireFox browser to not send the request properly!
Step 3: Receive server response
When the request is sent out, the server side starts executing, but the server-side response is not yet received. Next we will receive the response from the server.
The XMLHttpRequest object has a onreadystatechange event that is called when the state of the XMLHttpRequest object changes. Here are 5 states of the XMLHttpRequest object:
- 0: Initialize the incomplete state, just create object, open ()
- 1: The request has started, open () send ()
- 2 : Request send completion status, send () method called;
- 3: Start reading server response;
- 4: Read server response end. &NBSP;
The onReadyStateChange event is raised when the status is 1,2,3,4 .
The code below will be executed four times! Corresponds to the four states of XMLHttpRequest!
Xmlhttp.onreadystatechange = function () { alert (' Hello '); };
But usually we only care about the last state, that is, the client will make a change at the end of the read server response. We can get The state of the XMLHttpRequest object by XMLHttpRequest The ReadyState property of the object.
Xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate = = 4) { alert (' Hello ');} };
In fact, we also have to care about whether the server response status code is a number of, its server response is 404, or a few , then it means that the request failed. We can Get the status code of the server through the status property of the XMLHttpRequest object.
Finally, we also need to get the content of the server response, can get the server response content through the responsetext of the XMLHttpRequest object .
Xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate = = 4 && Xmlhttp.status = =) { alert (Xmlhttp.responsetext); } };
if send POST request
<1> need to set the request header:xmlHttp. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); Note: The form form will default to this key value pair, theWeb the server ignores the contents of the request body.
<2> can specify the request body when sending:xmlhttp.send ("Username=yuan&password=123")
JS Implementation Ajax Summary
/* Create the XMLHttpRequest object, call the Open () method to open the connection to the server, and call the Send () method to send the request; Specifies the onReadyStateChange event function for the XMLHttpRequest object, which is called when the XMLHttpRequest is 1, 2, 3, 4, four states; The 5 states of the XMLHttpRequest object, usually we only care about 4 states. the Status property of the XMLHttpRequest object represents the server state code, which is only available when readystate is 4 o'clock. the ResponseText property of the XMLHttpRequest object represents the server response content, which can only be obtained when readystate is 4 o'clock! */
varEle_btn=document.getelementsbytagname ("button") [0] Ele_btn.onclick=function () { //Send Ajax //(1) Get XMLHttpRequest objectXmlHttp =NewXMLHttpRequest (); //(2) connecting the server //Get //Xmlhttp.open ("Get", "/sendajax/?a=1&b=2"); //PostXmlhttp.open ("Post", "/sendajax/"); //set the Content-type of the request headerXmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); //(3) Send data varEle_csrf=document.getelementsbyname ("Csrfmiddlewaretoken") [0]; Ele_num1=document.getelementsbyclassname ("Num1") [0]; Ele_num2=document.getelementsbyclassname ("num2") [0]; Ele_ret=document.getelementsbyclassname ("ret") [0]; S1= "num1=" +Ele_num1.value; S2= "num2=" +Ele_num2.value; S3= "&csrfmiddlewaretoken=" +Ele_csrf.value; Xmlhttp.send (S1+ "&" +S2+S3);//Request Body Data //(4) Callback function SuccessXmlhttp.onreadystatechange =function() { if( This. readystate==4 && This. status==200) {Ele_ret.value= This. responsetext}}; }Ajax sends a GET request
varEle_btn=document.getelementsbytagname ("button") [0] Ele_btn.onclick=function () { //Send Ajax //(1) Get XMLHttpRequest objectXmlHttp =NewXMLHttpRequest (); //(2) connecting the server //Get //Xmlhttp.open ("Get", "/sendajax/?a=1&b=2"); //PostXmlhttp.open ("Post", "/sendajax/"); //set the Content-type of the request header varEle_csrf=document.getelementsbyname ("Csrfmiddlewaretoken") [0]; Xmlhttp.setrequestheader ("Content-type", "Application/json"); Xmlhttp.setrequestheader ("X-csrftoken", Ele_csrf.value); //(3) Send dataXmlhttp.send (' {' name ': ' Moses ', ' Age ': 22} ');//Request Body Data //(4) Callback function SuccessXmlhttp.onreadystatechange =function() { if( This. readystate==4 && This. status==200) {Console.log ( This. ResponseText)} }; }Ajax sends a POST request
Implementing AJAX requests with JS