In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the example analysis of the original request of ajax. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Introduction to XMLHttpRequest object
HTTP protocol is used to communicate between browser and server. The browser sends a HTTP request to the server when the user types a URL in the browser's address bar or submits content to the server through a web form.
In 1999, Microsoft released IE browser version 5.0, introducing a new feature for the first time: allowing JavaScript scripts to initiate HTTP requests to the server. This feature went unnoticed at the time and did not attract widespread attention until the release of Gmail in 2004 and Google Map in 2005. In February 2005, the word AJAX was formally put forward for the first time. It is the abbreviation of Asynchronous JavaScript and XML, which refers to extracting data from XML documents obtained from the server through the asynchronous communication of JavaScript, and then updating the corresponding part of the current web page without refreshing the whole web page. Later, the word AJAX became synonymous with JavaScript scripts to initiate HTTP communication, that is, as long as the script initiates communication, it can be called AJAX communication. The W3C also released its international standards in 2006.
Specifically, AJAX includes the following steps.
Create a XMLHttpRequest instance
Issue a HTTP request
Receive the data returned by the server
Update web page data
In a nutshell, AJAX makes a HTTP request through a native XMLHttpRequest object, gets the data returned by the server, and then processes it. Now, the data returned by the server is in JSON format, and the XML format is out of date, but the name AJAX has become a common noun and its literal meaning has disappeared.
The XMLHttpRequest object is the main interface of AJAX and is used for communication between browser and server. Although there are XML and Http in the name, it can actually use a variety of protocols (such as file or ftp) to send data in any format (including strings and binaries).
XMLHttpRequest itself is a constructor, and you can use the new command to generate an instance. It doesn't have any parameters.
Var xhr = new XMLHttpRequest ()
Once you create a new instance, you can use the open () method to specify some details of establishing a HTTP connection.
Xhr.open ('GET',' http://www.example.com/page.php', true)
The above code specifies that the GET method is used to establish a connection to the specified server URL. The third parameter, true, indicates that the request is asynchronous.
Then, specify a callback function to listen for changes in the communication state (the readyState property).
Xhr.onreadystatechange = handleStateChange;function handleStateChange () {/ /...}
In the above code, once the state of the XMLHttpRequest instance changes, the listener function handleStateChange is called
Finally, using the send () method, the request is actually made.
Xhr.send (null)
In the above code, the argument to send () is null, which means that the request is sent without a data body. If you are sending a POST request, you need to specify the data body here.
Once you get the data returned by the server, AJAX does not refresh the entire page, but only updates the relevant parts of the page, so as not to interrupt what the user is doing.
Note that AJAX can only issue HTTP requests to the same origin URL (protocol, domain name, port are all the same). If you send a cross-domain request, you will get an error (see "same Origin Policy" and "CORS Communications" for details).
The following is a complete example of the simple use of the XMLHttpRequest object.
Var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () {/ / the status value is 4 if (xhr.readyState = 4) {if (xhr.status = 200) {console.log (xhr.responseText);} else {console.error (xhr.statusText);}; xhr.onerror = function (e) {console.error (xhr.statusText);}; xhr.open ('GET',' / endpoint', true) Xhr.send (null); instance property XMLHttpRequest.readyState of XMLHttpRequest
XMLHttpRequest.readyState returns an integer that represents the current state of the instance object. This property is read-only. It may return the following values.
0, which means that the XMLHttpRequest instance has been generated, but the open () method of the instance has not been called.
1, indicating that the open () method has been called, but the instance's send () method has not been called yet, and you can still use the instance's setRequestHeader () method to set the header information of the HTTP request.
2, indicating that the send () method of the instance has been called, and the header information and status code returned by the server have been received.
3, indicating that the data body (body part) from the server is being received. At this point, if the responseType property of the instance is equal to text or an empty string, the responseText property will contain some of the information that has been received.
4, indicating that the data returned by the server has been fully received, or this reception has failed.
During communication, whenever the state of an instance object changes, the value of its readyState property changes. Each time this value changes, the readyStateChange event is triggered.
Var xhr = new XMLHttpRequest (); if (xhr.readyState = 4) {/ / request ends, processing the data returned by the server} else {/ / displays the prompt "loading." }
In the above code, when xhr.readyState equals 4, the HTTP request made by the script has been completed. In other cases, the HTTP request is still in progress.
XMLHttpRequest.onreadystatechange
The XMLHttpRequest.onreadystatechange property points to a listener function. This property is executed when the readystatechange event occurs (the readyState property of the instance changes).
In addition, if you use the instance's abort () method to terminate the XMLHttpRequest request, it will also cause the readyState property to change, resulting in a call to the XMLHttpRequest.onreadystatechange property.
Here is an example.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' http://example.com', true); xhr.onreadystatechange = function () {if (xhr.readyState! = = 4 | | xhr.status! = = 200) {return;} console.log (xhr.responseText);}; xhr.send (); XMLHttpRequest.response
The XMLHttpRequest.response attribute represents the body of data returned by the server (that is, the body part of the HTTP response). It can be any data type, such as strings, objects, binary objects, and so on, which is determined by the XMLHttpRequest.responseType property. The XMLHttpRequest.response property is read only.
If the request is unsuccessful or the data is incomplete, this attribute is equal to null. However, if the responseType property is equal to text or an empty string, the response property contains some of the data that has been returned by the server before the request is completed (the phase where readyState equals 3).
Var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () {if (xhr.readyState = 4) {handler (xhr.response);}} XMLHttpRequest.responseType
The XMLHttpRequest.responseType property is a string indicating the type of data returned by the server. This property is writable, and you can set the value of this property after calling the open () method and before calling the send () method, telling the browser how to interpret the returned data. If responseType is set to an empty string, it is equivalent to the default value of text.
The XMLHttpRequest.responseType property can be equal to the following values.
"(empty string): equivalent to text, indicating that the server returns text data.
"arraybuffer": an ArrayBuffer object that indicates that the server returns a binary array.
"blob": a Blob object that indicates that the server returns a binary object.
"document": a Document object that indicates that the server returns a document object.
"json": JSON object.
"text": string.
Of the above types, the text type is suitable for most situations, and it is convenient to work with text directly. The document type is suitable for returning HTML / XML documents, which means that for sites that open CORS, you can crawl the web page directly with Ajax, and then DOM the crawled data without parsing the HTML string. The blob type is suitable for reading binary data, such as image files.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' / path/to/image.png', true); xhr.responseType = 'blob';xhr.onload = function (e) {if (this.status = 200) {var blob = new Blob ([xhr.response], {type:' image/png'}); / / or var blob = xhr.response;}}; xhr.send ()
If you set this property to ArrayBuffer, you can process binary data as an array.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' / path/to/image.png', true); xhr.responseType = 'arraybuffer';xhr.onload = function (e) {var uInt8Array = new Uint8Array (this.response); for (var I = 0, len = uInt8Array.length; I)
< len; ++i) { // var byte = uInt8Array[i]; }};xhr.send(); 如果将这个属性设为json,浏览器就会自动对返回数据调用JSON.parse()方法。也就是说,从xhr.response属性(注意,不是xhr.responseText属性)得到的不是文本,而是一个 JSON 对象。 XMLHttpRequest.responseText XMLHttpRequest.responseText属性返回从服务器接收到的字符串,该属性为只读。只有 HTTP 请求完成接收以后,该属性才会包含完整的数据。 var xhr = new XMLHttpRequest();xhr.open('GET', '/server', true);xhr.responseType = 'text';xhr.onload = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); }};xhr.send(null);XMLHttpRequest.responseXML XMLHttpRequest.responseXML属性返回从服务器接收到的 HTML 或 XML 文档对象,该属性为只读。如果本次请求没有成功,或者收到的数据不能被解析为 XML 或 HTML,该属性等于null。 该属性生效的前提是 HTTP 回应的Content-Type头信息等于text/xml或application/xml。这要求在发送请求前,XMLHttpRequest.responseType属性要设为document。如果 HTTP 回应的Content-Type头信息不等于text/xml和application/xml,但是想从responseXML拿到数据(即把数据按照 DOM 格式解析),那么需要手动调用XMLHttpRequest.overrideMimeType()方法,强制进行 XML 解析。 该属性得到的数据,是直接解析后的文档 DOM 树。 var xhr = new XMLHttpRequest();xhr.open('GET', '/server', true);xhr.responseType = 'document';xhr.overrideMimeType('text/xml');xhr.onload = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseXML); }};xhr.send(null);XMLHttpRequest.responseURL XMLHttpRequest.responseURL属性是字符串,表示发送数据的服务器的网址。 var xhr = new XMLHttpRequest();xhr.open('GET', 'http://example.com/test', true);xhr.onload = function () { // 返回 http://example.com/test console.log(xhr.responseURL);};xhr.send(null); 注意,这个属性的值与open()方法指定的请求网址不一定相同。如果服务器端发生跳转,这个属性返回最后实际返回数据的网址。另外,如果原始 URL 包括锚点(fragment),该属性会把锚点剥离。 XMLHttpRequest.status,XMLHttpRequest.statusText XMLHttpRequest.status属性返回一个整数,表示服务器回应的 HTTP 状态码。一般来说,如果通信成功的话,这个状态码是200;如果服务器没有返回状态码,那么这个属性默认是200。请求发出之前,该属性为0。该属性只读。 200, OK,访问正常 301, Moved Permanently,永久移动 302, Moved temporarily,暂时移动 304, Not Modified,未修改 307, Temporary Redirect,暂时重定向 401, Unauthorized,未授权 403, Forbidden,禁止访问 404, Not Found,未发现指定网址 500, Internal Server Error,服务器发生错误 基本上,只有2xx和304的状态码,表示服务器返回是正常状态。 if (xhr.readyState === 4) { if ( (xhr.status >= 200 & & xhr.status < 300) | | (xhr.status = = 304) {/ / processing the returned data from the server} else {/ / error}}
The XMLHttpRequest.statusText property returns a string indicating the status prompt sent by the server. Unlike the status attribute, this property contains the entire state information, such as "OK" and "Not Found". Before the request is sent (that is, before the open () method is called), the value of this property is an empty string; if the server does not return a status prompt, the value of this property defaults to "OK". This property is read-only.
XMLHttpRequest.timeout,XMLHttpRequestEventTarget.ontimeout
The XMLHttpRequest.timeout property returns an integer indicating how many milliseconds later, if the request still does not get a result, it will be terminated automatically. If the attribute is equal to 0, there is no time limit.
The XMLHttpRequestEventTarget.ontimeout property is used to set a listener function that is executed if a timeout event occurs.
Here is an example.
Var xhr = new XMLHttpRequest (); var url ='/ server';xhr.ontimeout = function () {console.error ('The request for' + url + 'timed out.');}; xhr.onload = function () {if (xhr.readyState = 4) {if (xhr.status = 200) {/ / processing data returned by the server} else {console.error (xhr.statusText);}}; xhr.open (' GET', url, true) / / specify 10 second timeout xhr.timeout = 10 * 1000 X xhr.send (null); event listener attribute
The XMLHttpRequest object can specify a listener function for the following events.
Listener function for XMLHttpRequest.onloadstart:loadstart event (HTTP request issued)
Listener function for XMLHttpRequest.onprogress:progress event (sending and loading data)
Listener function for XMLHttpRequest.onabort:abort event (request abort, for example, the user called the abort () method)
Listener function for XMLHttpRequest.onerror:error event (request failed)
Listener function for XMLHttpRequest.onload:load event (request completed successfully)
Listener function for the XMLHttpRequest.ontimeout:timeout event (the time limit specified by the user has expired and the request has not been completed)
Listener function for XMLHttpRequest.onloadend:loadend event (request completion, regardless of success or failure)
Here is an example.
Xhr.onload = function () {var responseText = xhr.responseText; console.log (responseText); / / process the response.}; xhr.onabort = function () {console.log ('The request was aborted');}; xhr.onprogress = function (event) {console.log (event.loaded); console.log (event.total);}; xhr.onerror = function () {console.log (' There was an errorships');}
The listener function for the progress event has an event object parameter that has three properties: the loaded property returns the amount of data that has been transferred, the total property returns the total amount of data, and the lengthComputable property returns a Boolean value indicating whether the progress of the load can be calculated. Of all these listeners, only the listener for the progress event has arguments, and none of the other functions have arguments.
Note that if a network error occurs (such as the server is unreachable), the onerror event cannot get the error message. That is, there may be no error objects, so this can only display an error message.
XMLHttpRequest.withCredentials
The XMLHttpRequest.withCredentials attribute is a Boolean value indicating whether user information (such as Cookie and authenticated HTTP header information) will be included in the request when a cross-domain request is made. The default is false, that is, when a cross-domain request is issued to example.com, the Cookie (if any) whose example.com is set on the local machine will not be sent.
If you need to send Cookie for cross-domain AJAX requests, you need to set the withCredentials attribute to true. Note that requests of the same origin do not need to set this property.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' http://example.com/', true); xhr.withCredentials = true;xhr.send (null)
In order for this property to take effect, the server must explicitly return the header Access-Control-Allow-Credentials.
Access-Control-Allow-Credentials: true
When the withCredentials property is turned on, the cross-domain request not only sends a Cookie, but also sets the Cookie specified by the remote host. Vice versa, if the withCredentials property is not turned on, the browser will ignore cross-domain AJAX requests even if they explicitly require the browser to set Cookie.
Note that scripts always follow the same origin policy and cannot read the cross-domain Cookie,withCredentials attribute from the header information of [xss_clean] or HTTP responses. This does not affect this.
XMLHttpRequest.upload
XMLHttpRequest can not only send requests, but also send files, which is called AJAX file upload. After sending the file, you can get an object through the XMLHttpRequest.upload attribute, and by observing this object, you can see the progress of the upload. The main method is to listen for various events of this object: loadstart, loadend, load, abort, error, progress, timeout.
Suppose there is an element on the page.
0% complete
When uploading a file, specify the listening function of the progress event to the upload attribute to get the progress of the upload.
Function upload (blobOrFile) {var xhr = new XMLHttpRequest (); xhr.open ('POST',' / server', true); xhr.onload = function (e) {}; var progressBar = document.querySelector ('progress'); xhr.upload.onprogress = function (e) {if (e.lengthComputable) {progressBar.value = (e.loaded / e.total) * 100 / / compatible with older browsers that do not support elements progressBar.textContent = progressBar.value;}}; xhr.send (blobOrFile);} upload (new Blob (['hello world'], {type:' text/plain'})); XMLHttpRequest instance method XMLHttpRequest.open ()
The XMLHttpRequest.open () method is used to specify the parameters of the HTTP request, or to initialize the XMLHttpRequest instance object. It accepts a total of five parameters.
Void open (string method, string url, optional boolean async, optional string user, optional string password)
Method: denotes the verb method of HTTP, such as GET, POST, PUT, DELETE, HEAD, etc.
Url: indicates the URL to which the request is sent.
Async: a Boolean value indicating whether the request is asynchronous. The default is true. If set to false, the send () method does not take the next step until the server returns the result. This parameter is optional. Because synchronizing AJAX requests can cause browsers to become unresponsive, many browsers have banned it from the main thread and are only allowed to use it in Worker. Therefore, this parameter should not easily be set to false.
User: indicates the user name used for authentication. The default is an empty string. This parameter is optional.
Password: indicates the password used for authentication. The default is an empty string. This parameter is optional.
Note that if you use this method again for an AJAX request that has used the open () method, it is equivalent to calling abort (), which terminates the request.
Here is an example of sending a POST request.
Var xhr = new XMLHttpRequest (); xhr.open ('POST', encodeURI (' someURL')); XMLHttpRequest.send ()
The XMLHttpRequest.send () method is used to actually issue a HTTP request. Its parameters are optional. If there are no parameters, it means that the HTTP request has only one URL and no data body. A typical example is a GET request. If it has a parameter, it means that there is not only header information, but also an information body containing specific data. A typical example is a POST request.
The following is an example of an GET request.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' http://www.example.com/?id=' + encodeURIComponent (id), true); xhr.send (null)
In the above code, the parameters of the GET request are appended to the URL as a query string.
The following is an example of sending a POST request.
Var xhr = new XMLHttpRequest (); var data = 'email=' + encodeURIComponent (email) +' & password=' + encodeURIComponent (password); xhr.open ('POST',' http://www.example.com', true); xhr.setRequestHeader ('Content-Type',' application/x-www-form-urlencoded'); xhr.send (data)
Note that all listening events for XMLHttpRequest must be set before the send () method is called.
The argument to the send method is the data sent. Data in various formats can be used as its parameters.
Void send (); void send (ArrayBufferView data); void send (Blob data); void send (Document data); void send (String data); void send (FormData data)
If send () sends a DOM object, the data will be serialized before it is sent. If you send binary data, it is best to send an ArrayBufferView or Blob object, which makes it possible to upload files through Ajax.
Here is an example of sending form data. The FormData object can be used to construct form data.
Var formData = new FormData (); formData.append ('username',' Zhang San'); formData.append ('email',' zhangsan@example.com'); formData.append ('birthDate', 1940); var xhr = new XMLHttpRequest (); xhr.open (' POST','/ register'); xhr.send (formData)
In the above code, the FormData object constructs the form data and sends it using the send () method. It has the same effect as sending the form data below.
The following example uses a FormData object to process form data before sending it.
Function sendForm (form) {var formData = new FormData (form); formData.append ('csrf', 'e69a18d7db1286040586e6da1950128c'); var xhr = new XMLHttpRequest (); xhr.open (' POST', form.action, true); xhr.onload = function () {/...}; xhr.send (formData); return false;} var form = document.querySelector ('# registration'); sendForm (form); XMLHttpRequest.setRequestHeader ()
The XMLHttpRequest.setRequestHeader () method is used to set the header information of the HTTP request sent by the browser. This method must be called after open () and before send (). If the method is called multiple times and the same field is set, the value of each call is merged into a single value to send.
This method accepts two parameters. The first parameter is a string, which represents the field name of the header information, and the second parameter is the field value.
Xhr.setRequestHeader ('Content-Type',' application/json'); xhr.setRequestHeader ('Content-Length', JSON.stringify (data) .length); xhr.send (JSON.stringify (data))
The above code first sets the header information Content-Type to send data in JSON format, then sets Content-Length to represent the data length, and finally sends JSON data.
XMLHttpRequest.overrideMimeType ()
The XMLHttpRequest.overrideMimeType () method is used to specify the MIME type, overriding the real MIME type returned by the server, thus allowing the browser to handle it differently. For example, the data type returned by the server is text/xml. For various reasons, the browser parsing does not report an error successfully, and the data is not available. In order to get the raw data, we can change the MIME type to text/plain so that the browser does not parse automatically, so we can get the original text.
Xhr.overrideMimeType ('text/plain')
Note that this method must be called before the send () method.
Modifying the type of data returned by the server is not the normal way to do it. If you want the server to return the specified data type, you can tell the server with the responseType property, as in the following example. The overrideMimeType () method is used only if the server cannot return a data type.
Var xhr = new XMLHttpRequest (); xhr.onload = function (e) {var arraybuffer = xhr.response; /...} xhr.open ('GET', url); xhr.responseType =' arraybuffer';xhr.send (); XMLHttpRequest.getResponseHeader ()
The XMLHttpRequest.getResponseHeader () method returns the value of the specified field of the HTTP header information, and returns null if no response has been received from the server or the specified field does not exist. The parameters of this method are not case-sensitive.
Function getHeaderTime () {console.log (this.getResponseHeader ("Last-Modified"));} var xhr = new XMLHttpRequest (); xhr.open ('HEAD',' yourpage.html'); xhr.onload = getHeaderTime;xhr.send ()
If there are multiple fields with the same name, their values are concatenated as a string, each separated by a comma + space.
XMLHttpRequest.getAllResponseHeaders ()
The XMLHttpRequest.getAllResponseHeaders () method returns a string that represents all the HTTP header information sent by the server. The format is a string, and each header information is separated by CRLF (carriage return + line feed). If no response is received from the server, this attribute is null. If a network error occurs, the property is an empty string.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' foo.txt', true); xhr.send (); xhr.onreadystatechange = function () {if (this.readyState = 4) {var headers = xhr.getAllResponseHeaders ();}}
The above code is used to get all the header information returned by the server. It could be a string like this.
Date: Fri, 08 Dec 2017 21:04:30 GMT\ r\ ncontent-encoding: gzip\ r\ nx-content-type-options: nosniff\ r\ nserver: meinheld/0.6.1\ r\ nx-frame-options: DENY\ r\ ncontent-type: text/html; charset=utf-8\ r\ nconnection: keep-alive\ r\ nstrict-transport-security: max-age=63072000\ r\ nvary: Cookie, Accept-Encoding\ r\ ncontent-length: 6502\ r\ nx-xss-protection: 1; mode=block\ r\ n
Then, the string is processed.
Var arr = headers.trim (). Split (/ [\ r\ n] + /); var headerMap = {}; arr.forEach (function (line) {var parts = line.split (':'); var header = parts.shift (); var value = parts.join (':'); headerMap [header] = value;}); headerMap ['content-length'] / / "6502" XMLHttpRequest.abort ()
The XMLHttpRequest.abort () method is used to terminate an HTTP request that has already been made. After calling this method, the readyState property changes to 4, and the status property changes to 0.
Var xhr = new XMLHttpRequest (); xhr.open ('GET',' http://www.example.com/page.php', true); setTimeout (function () {if (xhr) {xhr.abort (); xhr = null;}}, 5000)
The above code terminates an AJAX request 5 seconds after it is issued.
Event of the XMLHttpRequest instance readyStateChange event
The readyStateChange event is triggered when the value of the readyState property changes.
We can specify the listener function for this event through the onReadyStateChange property to handle different states differently. Especially when the state changes to 4, the communication is successful, and the callback function can process the data sent back by the server.
Progress event
When uploading a file, both the XMLHttpRequest instance object itself and the upload attribute of the instance have a progress event, which will constantly return the progress of the upload.
Var xhr = new XMLHttpRequest (); function updateProgress (oEvent) {if (oEvent.lengthComputable) {var percentComplete = oEvent.loaded / oEvent.total;} else {console.log ('cannot calculate progress');} xhr.addEventListener ('progress', updateProgress); xhr.open (); load event, error event, abort event
The load event indicates that the data from the server has been received, the error event indicates an error in the request, and the abort event indicates that the request was interrupted (for example, the user canceled the request).
Var xhr = new XMLHttpRequest (); xhr.addEventListener ('load', transferComplete); xhr.addEventListener (' error', transferFailed); xhr.addEventListener ('abort', transferCanceled); xhr.open (); function transferComplete () {console.log (' data received');} function transferFailed () {console.log ('data reception error');} function transferCanceled () {console.log ('user cancels receiving');} loadend event
The three events, abort, load, and error, are accompanied by a loadend event indicating that the request is over, but it is not known whether it was successful or not.
Xhr.addEventListener ('loadend', loadEnd); function loadEnd (e) {console.log (' request ended, status unknown');} timeout event
The timeout event will be triggered when the server does not return a result after the specified time. For a specific example, see the timeout properties section.
Navigator.sendBeacon ()
When users uninstall a web page, they sometimes need to send some data to the server. It is natural to use the XMLHttpRequest object to send data in the listener function of the unload event or beforeunload event. However, this is not very reliable because the XMLHttpRequest object is sent asynchronously, and it is likely that the page has been unloaded by the time it is about to be sent, causing the send to be canceled or failed.
The solution is to add some time-consuming synchronization operations to the unload event. This allows enough time to ensure that the asynchronous AJAX can be sent successfully.
Function log () {let xhr = new XMLHttpRequest (); xhr.open ('post',' / log', true); xhr.setRequestHeader ('Content-Type',' application/x-www-form-urlencoded'); xhr.send ('foo=bar');} window.addEventListener (' unload', function (event) {log (); / / a time-consuming operation for (let I = 1; I < 10000; iTunes +) {for (let m = 1; m < 10000; masks +) {continue })
In the above code, a double loop is enforced, which lengthens the execution time of the unload event, causing the asynchronous AJAX to be sent successfully.
Similarly, you can use setTimeout. The following is an example of tracking user clicks.
/ / the HTML code is as follows / / clickconst clickTime = 350 Const theLink = document.getElementById ('target'); function log () {let xhr = new XMLHttpRequest (); xhr.open (' post','/ log', true); xhr.setRequestHeader ('Content-Type',' application/x-www-form-urlencoded'); xhr.send ('foo=bar');} theLink.addEventListener (' click', function (event) {event.preventDefault (); log () SetTimeout (function () {_ window.location.href = theLink.getAttribute ('href');}, clickTime);})
The above code uses setTimeout, which takes 350 milliseconds to make the page jump, thus giving the asynchronous AJAX time to issue.
The common problem with these practices is that the unloading time has been rigidly prolonged, the loading of later pages has been delayed, and the user experience is not good.
To solve this problem, the browser introduces the Navigator.sendBeacon () method. This method still makes the request asynchronously, but the request is decoupled from the current page thread as a task of the browser process, so it is guaranteed that the data will be sent without delaying the uninstall process.
Window.addEventListener ('unload', logData, false); function logData () {navigator.sendBeacon (' / log', analyticsData);}
The Navigator.sendBeacon method accepts two parameters, the first is the URL of the target server, and the second is the data to be sent (optional), which can be of any type (string, form object, binary object, and so on).
Navigator.sendBeacon (url, data)
The return value of this method is a Boolean value, and the data sent successfully is true, otherwise it is false.
The HTTP method of this method to send data is POST, which can be cross-domain, similar to a form submitting data. It cannot specify a callback function.
Here is an example.
/ / the HTML code is as follows / / function analytics (state) {if (! navigator.sendBeacon) return; var URL = 'http://example.com/analytics'; var data =' state=' + state +'& location=' + _ window.location; navigator.sendBeacon (URL, data) } this is the end of the article on "sample Analysis of ajax original request". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.