English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
XMLHttpRequest makes it very easy to send an HTTP request. You just need to create an instance of a request object, open a URL, and then send this request. After the transfer is complete, the HTTP status of the result 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 the third parameter async 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 is completed asynchronously.
Two communication modes:Synchronous and asynchronous requests:
Synchronous request
Synchronous requests in the main thread will block the page, and due to the poor user experience, some of the latest browsers have deprecated synchronous requests in the main thread. In rare cases, using synchronous XMLHttpRequests may be more suitable than using asynchronous mode.
1It is more suitable to use synchronous requests than asynchronous requests when using XMLHttpRequest in a Worker.
Code on 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 requested synchronously by the XMLHttpRequest object): Hello World!!
Contains 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 Workers are used, the request is actually also asynchronous.
Similar methods can be used to allow scripts to interact with the server in the background, preloading some content. See more details about using web workers
2. Situations where synchronous requests must be used
In some rare cases, only synchronous mode XMLHttpRequest requests can be used. For example, in the event handler functions of window.onunload and window.onbeforeunload. Using asynchronous XMLHttpRequest in the page unload event handler can cause such a problem: after the response is returned, the page no longer exists, and all variables and callback functions have been destroyed. The result will only cause an error, "Function is not defined". The solution is to use synchronous mode requests here, so that the page will not be closed before the request is completed.
window.onbeforeunload = function () { var oReq = new XMLHttpRequest(); oReq.open("GET", "logout.php"63;nick=" + escape(myName), false); // Synchronous request oReq.send(null); if (oReq.responseText.trim() !== "Exited"); { // "Exited" is the returned data return "Failed to exit, do you want to exit manually?"63;"; } });
Asynchronous request
When using asynchronous mode, a specified callback function will be executed after the data is completely requested, while the browser can normally execute other transaction processing at the same time.
3. Example: Create a standard method to read external files
In some cases, it is necessary to read multiple external files. This is a standard function. The function uses the XMLHttpRequest object for asynchronous requests and can specify different callback functions for each file read completion.
function loadFile (sURL, timeout, fCallback /*, passing parameters1, passing parameters2, 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); } ; 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");
Chapter1Define a function that will be called when the file is read, fCallback will be called with the3The remaining parameters are called with their own parameters.
Chapter3to avoid your code executing for a long time waiting to read the response data, set a timeout by assigning a value to the timeout property of the XMLHttpRequest object.
Chapter6event handler specifies the callback function, which checks whether the request has ended (is the request state4, if so, determine whether the request was successful (is the HTTP status code200), if so, output the page source code, and if the request encounters an error, output the error information.
Chapter15Specify the third parameter as true to indicate that the request should be executed asynchronously.
4. Example: Use asynchronous requests without closures.
function switchXHRState() { switch (this.readyState) { case 0: console.log("open() method not called."); break; case 1: console.log("send() method not called."); break; case 2: console.log("send() method called, response headers and status have been returned."); break; case 3: console.log("Downloading, received a partial response entity."); break; case 4; console.log("Request completed!"); this.callback.apply(this, this.arguments); } }); function loadFile (sURL, fCallback /*, passing parameters1, passing parameters2, 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("open() method not called."); break; case 1: console.log("send() method not called."); break; case 2: console.log("send() method called, response headers and status have been returned."); break; case 3: console.log("Downloading, received a partial response entity."); break; case 4: console.log("Request completed!"); fCallback.apply(this, aArguments); } }); function loadFile (sURL, fCallback /*, passing parameters1, passing parameters2, 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); }
That's all for the content of this article. I hope it will be helpful to everyone's study, and I also hope everyone will support the Yelling Tutorial more.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)