This time I will show you how AJAX implements asynchronous refresh and partial refresh. What are the precautions for AJAX to implement asynchronous refresh and partial refresh? The following is a practical case, let's take a look.
Overriew: onReadyStateChange is assigned by thecallback function, and asynchronous calls can be realized. The callback function directly operates the DOM, and partial refresh can be realized. So how does XMLHttpRequest's onReadyStateChange know that the service is ready? How does the state change (Observer Mode)? This is achieved through the client's status inquiry (periodic polling) of the service.
Detailed explanation:
1. XMLHttpRequest is responsible for communication with the server, and there are Many important attributes: readyStatus=4, status=200, etc. When the overall status of XMLHttpRequest is guaranteed to be completed (readyStatus=4), the data has been sent. Then query the request status according to the server's settings (similar to the client polling the server's return status, which is still an http short connection, not a long connection server-side push). If everything is ready (status=200), then execute required operation.
The operation is generally to directly operate the DOM, so AJAX can achieve the so-called "no refresh" user experience.document.getElementById("user1").innerHTML = "数据正在加载..."; if (xmlhttp.status == 200) { document.write(xmlhttp.responseText); }
2. So how to do it asynchronously on the AJAX client? In fact, it is the role of the callback function of Javascript
Provides a callback JavaScript function, which is executed once the server response is availableBusiness function:
function castVote(rank) { var url = "/ajax-demo/static-article-ranking.html"; var callback = processAjaxResponse; executeXhr(callback, url); } 需要异步通讯的函数: function executeXhr(callback, url) { // branch for native XMLHttpRequest object if (window.XMLHttpRequest) { req = new XMLHttpRequest(); req.onreadystatechange = callback; req.open("GET", url, true); req.send()(null); } // branch for IE/Windows ActiveX version else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); if (req) { req.onreadystatechange = callback; req.open("GET", url, true); req.send()(); } } } req.onreadystatechange = callback req.open("GET", url, true)
Callback function:
function processAjaxResponse() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById("user1").innerHTML = req.responseText; } else { alert("There was a problem retrieving the XML data: " + req.statusText); } } }
laypage paging plug-in + ajax how to make asynchronous paging
JS+ajax implements php asynchronous submission Form
The above is the detailed content of How to implement asynchronous refresh and partial refresh in AJAX. For more information, please follow other related articles on the PHP Chinese website!