XMLHttpRequest makes sending an HTTP request very easy. You just need to simply create an instance of the request object, open a URL, and then send the request. After the transmission is completed, the resultant HTTP status and the returned response content can also be obtained from the request object.
Requests generated by XMLHttpRequest can be obtained in two ways, asynchronous mode or synchronous mode. The type of request is determined by the value of async, the third parameter of the open() method of this XMLHttpRequest object. If the value of this parameter is false, the XMLHttpRequest request is performed in synchronous mode, otherwise the process will be completed in asynchronous mode.
Two communication modes: synchronous and asynchronous requests:
Synchronize requests
Synchronization requests in the main thread block the page, and due to poor user experience, synchronization requests on the main thread of some latest browsers have been deprecated. In rare cases, XMLHttpRequests using synchronous mode will be more suitable than using asynchronous mode.
1. When using XMLHttpRequest in Worker, synchronous requests are more suitable than asynchronous requests.
Code in the homepage:
<script type="text/javascript"> var oMyWorker = new Worker("myTask.js"); oMyWorker.onmessage = function(oEvent) { alert("Worker said: " + oEvent.data); }; oMyWorker.postMessage("Hello");</script>myFile.txt (the file that synchronizes the requested XMLHttpRequest object): Hello World!!Includes Worker code: myTask.js
self.onmessage = function (oEvent) { if (oEvent.data === "Hello") {var oReq = new XMLHttpRequest();oReq.open("GET", "myFile.txt", false); // Synchronous request oReq.send(null);self.postMessage(oReq.responseText); }};Note: Since Worker is used, the request is actually asynchronous.
Similar methods can be used to allow scripts to interact with the server in the background and preload certain content. Check out the use of web workers for more details
2. The situation where synchronous requests have to be used
In rare cases, only synchronous mode XMLHttpRequest requests can be used. For example, in the window.onunload and window.onbeforeunload event handling functions. Using asynchronous XMLHttpRequest in the unload event handler function of the page will cause the problem: when the response is returned, the page no longer exists, and all variables and callback functions have been destroyed. The result can only cause an error, "function is not defined". The solution is to use the request in synchronization mode here, so that the page will not be closed until the request is completed.
window.onbeforeunload = function () { var oReq = new XMLHttpRequest(); oReq.open("GET", "logout.php?nick=" + escape(myName), false); // Synchronous request oReq.send(null); if (oReq.responseText.trim() !== "Exited"); { // "Exited" is the returned data return "Exit failed, do you want to manually execute the exit?"; }};Asynchronous request
If you use asynchronous mode, when the data is completely requested, a specified callback function will be executed. While executing the request, the browser can normally execute other transactions.
3. Example: Create a standard method to read external files
In some requirements, multiple external files must be read. This is a standard function. This function uses the XMLHttpRequest object for asynchronous requests. It also allows you to specify a different callback function after each file read is completed.
function loadFile (sURL, timeout, fCallback /*, pass in parameter 1, pass in parameter 2, etc. */) { var aPassArgs = Array.prototype.slice.call(arguments, 3), oReq = new XMLHttpRequest(); oReq.ontimeout = function() {console.log("Request timeout."); } oReq.onreadystatechange = function() {if (oReq.readyState === 4) { if (oReq.status === 200) { fCallback.apply(oReq, aPassArgs); } else { console.log("Error", oReq.statusText); }} }; oReq.open("GET", sURL, true); oReq.timeout = timeout; oReq.send(null);}Usage of loadFile function:
function showMessage (sMsg) { alert(sMsg + this.responseText);}loadFile("message.txt", 200, showMessage, "New message!//n");Line 1 defines a function. After the file is read, the fCallback function will be called with all parameters after the third parameter as its own parameters.
Line 3 uses a timeout setting to avoid your code from executing long-term execution of the return data of the read request. By assigning a value to the timeout property of the XMLHttpRequest object to the timeout property
The sixth behavior onreadystatechange event handle specifies the callback function. Each time the function executes, checks whether the request ends (the request status is 4). If so, determines whether the request is successful (the HTTP status is 200). If so, outputs the page source code. If an error occurs, outputs the error message.
Line 15 specifies that the third parameter is true, indicating that the request should be executed in asynchronous mode.
4. Example: Use asynchronous requests, no closures are used.
function switchXHRState() { switch (this.readyState) {case 0: console.log("The open() method has not been called yet."); break;case 1: console.log("The send() method has not been called yet."); break;case 2: console.log("The send() method has been called, the response header and response status have been returned."); break;case 3: console.log("Download, part of the response entity has been obtained."); break;case 4: console.log("Request completed!"); this.callback.apply(this, this.arguments); }};function loadFile (sURL, fCallback /*, pass in parameter 1, pass in parameter 2, etc. */) { var oReq = new XMLHttpRequest(); oReq.callback = fCallback; oReq.arguments = Array.prototype.slice.call(arguments, 2); oReq.onreadystatechange = switchXHRState; oReq.open("GET", sURL, true); oReq.send(null);}Use bind:
function switchXHRState(fCallback, aArguments) { switch (this.readyState) { case 0: console.log("The open() method has not been called."); break;case 1: console.log("The send() method has not been called."); break;case 2: console.log("The send() method has been called, the response header and response status have been returned."); break;case 3: console.log("The partial response entity has been obtained during download."); break;case 4: console.log("Request completed!"); fCallback.apply(this, aArguments); }};function loadFile (sURL, fCallback /*, pass in parameter 1, pass in parameter 2, etc. */) { var oReq = new XMLHttpRequest(); oReq.onreadystatechange = switchXHRState.bind(oReq, fCallback, Array.prototype.slice.call(arguments, 2)); oReq.open("GET", sURL, true); oReq.send(null);}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.