1.
function ajax (URL, onsuccess) {varxmlhttp = window. XMLHttpRequest?NewXMLHttpRequest ():NewActiveXObject ('Microsoft.XMLHTTP');//Create XMLHTTP objects, consider compatibility. XHRXmlhttp.open ("POST"Urltrue);//prepare to issue a POST request to the server's GETDATE1.ASHX (get may have a caching problem). No request has been made here yet .//DRY: Do not copy and paste code//Ajax is asynchronous, not waiting for server-side return to continue executionXmlhttp.onreadystatechange =function () {if(Xmlhttp.readystate = =4)//ReadyState = = 4 indicates that the server has returned the completed data. may have experienced 2 before (request sent, in process), 3 (part of the data in response is available, but the server has not completed a response generation) { if(Xmlhttp.status = = $)//if the HTTP status code is 200 it is successful{onsuccess (xmlhttp.responsetext); } Else{alert ("The AJAX server returned an error! "); } } } //do not think if (xmlhttp.readystate = = 4) {Execute before send!!!! Xmlhttp.send ();//This is the time to start sending requests. is not equal to server-side return. Request sent out, I wait! Listen to onReadyStateChange! }
JS Asynchronous Request Encapsulation