JS Asynchronous Request Encapsulation

Source: Internet
Author: User

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

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.