Common ajax Request Method encapsulation, compatible with mainstream browsers
Ajax Introduction
What if there is no AJAX? Normal ASP. Net refreshes the current page every time the server method is executed. Without AJAX, if you click "Top, step", comment, or comment to flip the page while watching the video in youku, the page will be refreshed and the video will be interrupted. Develop an effect: Use Play a video (only html5 browsers can play the video), and then put a "like" button (the number of likes is saved to the database). If ajax is not used, the video will be interrupted, but not Youku.
AJAX is a technology that performs partial asynchronous page refreshing. When AJAX is used to send requests to the server and obtain the data returned by the server and update the data to the interface, the whole page is not refreshed, instead, you can use JavaScript to create an XMLHTTPRequest object on the HTML page to send requests to the server and obtain the returned data, just like the JavaScript version of WebClient, in the page, XMLHTTPRequest sends an Http request and obtains the server's returned data, so that the page will not be refreshed. XMLHTTPRequest is the core object of AJAX.
There are some repeated items that we do not want to manually re-write or re-copy each time. In this case, we need to encapsulate the code. Method encapsulation principle: encapsulate the unchanged code and pass the changed content as a parameter.
// Url: the ajax request address contains the parameters to be passed. onsuccess: The js method function ajax (url, onsuccess) executed after the request is successful {var xmlhttp = window. XMLHttpRequest? New XMLHttpRequest (): new ActiveXObject ('Microsoft. xmlhttp'); // create an XMLHTTP object and consider compatibility. XHR xmlhttp. open ("POST", url, true); // "prepare" sends a Post request to the server's GetDate1.ashx (GET may cause cache problems ). No request has yet been sent // DRY: do not copy or paste the code // AJAX is asynchronous, and the execution of xmlhttp will not continue until the server returns. onreadystatechange = function () {if (xmlhttp. readyState = 4) // readyState = 4 indicates that the server has returned complete data. May have gone through 2 (the request has been sent and is being processed), 3 (some data is available in the response, but the server has not yet completed the response generation) {if (xmlhttp. status = 200) // If the Http status code is 200, it is successful {onsuccess (xmlhttp. responseText);} else {alert ("error returned by AJAX server! ") ;}}// Do not think that if (xmlhttp. readyState = 4) {execute before sending !!!! Xmlhttp. send (); // The request is sent. Does not mean that the server returns. The request has been sent. I am not waiting! Listen to onreadystatechange !}