The underlying implementation principle of Ajax

Source: Internet
Author: User
Tags bind http request
the current prevalence of AjaxThe AJAX framework is so numerous that Ajax is so big that it even has its parents JavaScripthave been brought up, remember when I first touched the web when JavaScript has not reached the height of today, as customer reminders are becoming more and more important, many software development is not just to stay on the requirements of functional implementation, but rather focus on interaction, sharing and interaction (this is web2.0 's goal). In fact, this is completely correct, after all, the only thing that gives the function we can not satisfy, for example, you buy things also want to pick good, not to mention software development. Back to the point, the AJAX framework I'm still in favor of using, after all, to achieve efficiency is too slow, like the current excellent JavaScript Framework JQueryHave to be appreciated, and it is also becoming more and more popular, even Microsoft is in the ASP . NETThe MVC framework comes with jquery. But I think it is necessary to understand the nature of Ajax, so that you can freely. the work of AjaxAjax Intuition Understanding: We send a request, but this request is more special it is asynchronous, that is, the client will not feel. When we send this request we bind an event that monitors the state of our sending request, and each time a state change is triggered, so that we can perform different actions depending on the state. The request arrives at the server side after the server side returns the corresponding information according to the corresponding request, this return information we can obtain and is asynchronously obtains, does not cause the client to flush. Now that we have bound the events that monitor the change of state, we can do the processing in the first place to get the return information (if the failure has a corresponding state we will also do the corresponding processing), we get the return information in the process through JavaScript to do the corresponding action on the client. Ajax Core —-----XMLHttpRequestWe probably felt the Ajax process above, and we found that sending an asynchronous request was the core, in fact it was xmlhttprequest, and the whole Ajax was able to complete the asynchronous request entirely because the correspondence could send an asynchronous request. And we found that the above event is the core of the entire processing process, can be carried out according to different state of operation, in fact, it is XMLHttpRequest method onreadystatechange, it will be triggered every time the state changes. So who gets the return information? It's another way of XMLHttpRequest responsetext (and Responsexml, of course). (⊙o⊙) Oh, we haven't said who to send to and perform the send operation, these two are XMLHttpRequest's open and send methods. Y (^o^) y, and of course the rest, let's just list it:
XMLHttpRequest Object Properties readyState:The request status, the start request value is 0 until the request is completed this value grows to 4 ResponseText:The response body received so far, readystate<3 this property is an empty string, =3 is the current response body, and =4 is the full response body Responsexml:Server-side, parse to XML and return as document object Status:Server-side returned status code, =200 successful, =404 "not Found" statustext:Server-side return status by name, "Not Found" is 400 for "OK"
Method setRequestHeader ():Set header information to a request that opens but does not occur open ():Initialize request parameters but not send Send ():Send HTTP request abort ():Cancels the current corresponding getallresponseheaders ():Returns the HTTP corresponding header as an unresolved string getResponseHeader ():Returns the value of the corresponding header of the HTTP
Event Handle onreadystatechange:This event handle is called every time readystate changes, but when readystate=3 is likely to be called multiple times Code ImplementationAjax.js file code, is also the main content we say, is a JavaScript file, all the Ajax operations are here: //Communication with the serverfunction Talktoserver (URL) {var req = Newxmlhttprequst (); var callbackhandler = Getreadystatehandler (req); req.onreadyst Atechange = CallbackHandler; Req.open ("POST", url, True); Req.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); var testmsg = document.getElementById ("testmsg"); var msg_value = Testmsg.value; Req.send ("msg=" +msg_value); } //Create XMLHTTP Objectfunction Newxmlhttprequst () {var xmlreq = false, if (window). XMLHttpRequest) {xmlreq = new XMLHttpRequest ();} else if (window. ActiveXObject) {try{xmlreq=new ActiveXObject ("Msxm12.xmlhttp"),} catch (E1) {try {xmlreq = new ActiveXObject ("Microso Ft. XMLHTTP "); } catch (E2) {}}} return xmlreq; } //Server callback function function Getreadystatehandler (req) {return function () {if (req.readystate = = 4) {if (Req.status = =) {var msg_disp Lay = document.getElementById ("Msg_display"); msg_display.innerhtml = Req.responsetext; } else {var hellomsg = document.getElementById ("hellomsg"); hellomsg.innerhtml = "ERROR" + Req.status;}} }}     Other related code is also posted so that you can correctly execute       use the Ajax.js code, which is the Default.aspx foreground code:  <%@ page language= "C #" autoeventwireup= "true" codebehind= "Default.aspx.cs" inherits= "Myfirst._default"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> from the code we can see: first we create a XMLHttpRequest object (because the browser needs the corresponding judgment processing), set the corresponding request information (through open to do, such as request address settings); Then we bind the onReadyStateChange event , in this event we make different processing according to the different status of the server return, which is mainly to receive the corresponding return value after the request succeeds to the client through JavaScript (we just make the information display); Finally we send the request (via the Send method). Summary with the above description and code implementation we find that the fact that the entire Ajax-free function is done using XMLHttpRequest's asynchronous request. The key is that we understand the relevant member information of XMLHttpRequest. Of course, we said that in the actual development if it is not cost-effective to write the code manually, we can choose the appropriate framework for AJAX development. OK, let's get here.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.