Ajax journey (iii) -- asynchronous update and ajax journey
In the previous blog, I have already explained in theory what is the XMLHttpRequest object, which is the core object for Ajax asynchronous update. Next, we will use an instance to understand how to use the XMLHTTPRequest object orAsynchronous update Implementation.
Instance: judge whether the user code is repeated
Solution 1: Synchronize updates.Shows the principle:
We can see that when we enter "User code" in the browser user code input box, we can only wait for the response from the server,After the server returns the result to the browser, we can perform the next operation.That is, enter the "user name ".
This is a synchronous update, which will inevitably give the user a few seconds of waiting time. Maybe there is nothing in an input box. If you enter something every time, you have to wait for a few seconds, even a second, are there any other users willing to continue using our website? So asynchronous and new.
Solution 2: asynchronous update, As shown in the following figure:
We can see that it is significantly different from synchronous update. In asynchronous updates, we use the Ajax engine, which seems to be,Adding an intermediate layer (Ajax engine) to the browser and Server).
In this way, after entering the "user code", the browser sends the request to the Ajax engine, and then you can continue entering the "user name,No longer waiting. The Ajax engine then sends the request to the server. After the server operation is complete, return the result to the Ajax engine. The Ajax engine then returns the result to the browser for display. In short,The browser only needs to send the request to Ajax, and then what to do and what to do. When the Ajax engine is updated, the callback function is used to return the request to the browser. This is asynchronous update.
Through solution 1, we obviously know the advantages of solution 2. How can we implement it in code, the following are some code implementations that I use to determine whether the user code is repeated for your reference. Of course, these implementations are also used to give readers a deep understanding of the use of XMLHttpRequest objects.
Step 1: Create the core Ajax object XMLHttpRequest.
Here, we need to make different instantiation results for different browsers.
<Span style = "font-size: 18px;"> var xmlHttp; function createXMLHttpRequest () {// indicates that the current browser is not ie if (window. XMLHttpRequest) {xmlHttp = newXMLHttpRequest ();} else if (window. activeXObject) {xmlHttp = newActiveXObject ("Microsoft. XMLHTTP ") ;}}</span>
Step 2: register the callback function.
The callback function is the core method for implementing asynchronous update of the XMLHttpRequest object. After a request is sent, the client cannot determine when the request will be completed. Therefore, an event mechanism is required to capture the Request status. The XMLHttpRequest object provides the onreadyStateChange event to implement this function, that is, the callback function.
In other words:The callback is called by the server instead of by you.(This is called by the Ajax engine .)
<Span style = "font-size: 18px;"> <span style = "font-size: 14px;"> // registers the callback function xmlHttp. onreadystatechange = callback; </span>
Note the following:
<Span style = "font-size: 18px;"> xmlHttp. onreadystatechange = callback (); // indicates the method to call xmlHttp. onreadystatechange = callback; // indicates passing the method address </span>
Step 3: Set the interaction mode and corresponding parameters with the server.
The code implementation varies according to different submission methods. The Implementation below is the code submitted by get. There is also a parameter, xmlHttp. open ("GET", url,True), True indicates asynchronous submission, and false indicates synchronous submission,To Implement Asynchronous update, set this parameter to true..
<Span style = "font-size: 18px;"> // Step 3: Set the interaction mode with the server and the corresponding parameter varurl = "user_validate.jsp? UserId = "+ trim (filed. value) +" & time = "+ new Date (). getTime () </span>
<span style="font-size:18px;"> xmlHttp.open("GET", url, true);</span>
Step 4: send data to the server.
After the preceding settings are complete, we only need to send data to the server.
<Span style = "font-size: 18px;"> // Step 4: send data to the server xmlHttp. send (null);} else {document. getElementById ("spanUserId "). innerHTML = "" ;}</span>
Step 5: Use the callback function to determine whether the interaction with the server is complete, whether the response is correct, and update the page content based on the data returned by the server.
<Span style = "font-size: 18px;"> // Step 5: Determine whether the interaction with the server has completed functioncallback () {if (xmlHttp. readyState = 4) {if (xmlHttp. status = 200) {if (trim (xmlHttp. responseText )! = "") {// Alert (xmlHttp. responseText); document. getElementById ("spanUserId "). innerHTML = "<fontcolor = 'red'>" + xmlHttp. responseText + "</font>"} else {document. getElementById ("spanUserId "). innerHTML = "" ;}} else {alert ("request failed. Error Code: "+ xmlHttp. status) ;}}</span>
Note:
<Span style = "font-size: 18px;"> ajax. readyState = 4 // a response is returned. Whether it is correct or not; Ajax engine status is successful ajax. status = 200 // HTTP protocol status is successful </span>
After five steps, we can determine whether the user code has repeated asynchronous updates. I don't know how much you know about Ajax, XMLHttpRequest objects, and asynchronous updates?
How does AJAX Implement Asynchronous refresh?
This will explain to you.
First, when we open a URL address, we directly enter it in the address bar of the browser. After we press enter, the corresponding content of the server will be displayed in the browser. That is to say, when a regular browser opens a URL address, the browser is required.
What Is Ajax? It actually uses the XMLHttpRequest object in JavaScript to open a URL address, and then read the content returned from the URL address. In other words, we can use another window to open it, through js, you can open a URL address and obtain the response information. After this information is captured by JS, it can be combined by JS according to a rule and displayed on the page. This process is called Ajax asynchronous refresh.
To truly feel this process, you have to perform actual operations with js.
Let me compile an example for you. Let's take a look:
========================================================== ==================
/**
* Create an XMLHttpRequest object
* @ Return
* This object is returned if creation is successful. Otherwise, null is returned.
*/
Function createXMLHttpRequest (){
Var xmlHttpReq = null;
If (window. XMLHttpRequest) {// IE7 and later versions, FF, and other browser window objects have XMLHttpRequest sub-objects
XmlHttpReq = new XMLHttpRequest ();
} Else {
If (window. ActiveXObject) {// IE6 and earlier versions do not have XMLHttpRequest, but it can create this object through ActiveXObject
Try {
XmlHttpReq = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){
Try {
XmlHttpReq = new ActiveXObject ("Msxml12.XMLHTTP ");
} Catch (e ){
}
}
}
}
Return xmlHttpReq;
}
/**
* Send a request to a specified address
* @ Param url
* URL of the request to be sent
*/
Function sendRequest (url ){
Var xmlHttpReq = createXMLHttpRequest ();
If (xmlHttpReq ){
XmlHttpReq. open ("GET", url, true );
XmlHttpReq. onreadystatechange = function (){
If (xmlHttpReq. readyState = 4 ){
If (xmlHttpReq. status = 200 ){
Var out = "";
Var res = XMLHttpReq. responseText;
Alert ("Server Response string:" + res );
}
}
};
XmlHttpReq. send (null );
}
}
/**
* Call Ajax to send a request to the server, where
*./Pages/userlist. jsp? Sid = 12
* Is the URL to be requested... the remaining full text>
Asynchronous ajax page refresh
Use ajax, 100% to meet your needs!
Below I will provide you with an asynchronous request source code in js:
Function isExist (){
Var companyName = $ ("# company"). val ();
If (companyName = ""){
Alert ("'Company 'cannot be blank! ");
$ ("# Company"). focus ();
Return;
}
Var num = 0;
$. Ajax ({
Url: "isExistCompany. do? Company. companyName = "+ companyName +" & t = "+ new Date (),
Async: false,
Success: function (data ){
Num = data;
}
});
If (num = 0 ){
Alert ("the company you entered does not exist. Please enter it again! ");
$ ("# Company"). val ("")
$ ("# Company"). focus ();
Return false;
}
Return true;
}
In action: public void isExistCompany (){
Try {
Int num = 0;
String companyName = company. getCompanyName ();
If (company! = Null | StringUtil. notEmpty (companyName ))
Num = companyService. getCompanyId (companyName );
HttpServletResponse response = ServletActionContext. getResponse ();
Response. setContentType ("text/plain; charset = GBK ");
PrintWriter out = response. getWriter ();
Out. print (num );
Out. flush ();
} Catch (Exception e ){
E. printStackTrace ();
}
}