XHR, jquery, and AXIos cancel asynchronous requests as follows:
1.XHR
The key to canceled Ajax for native XHR objects is to call the.abort() method on the XHR object
var xhr = new XMLHttpRequest(); / / object (1) create asynchronous XHR. Open (" GET ", "https://api.github.com/"); // (2) Set the request parameters. Include: request method, request URL xhr.send(); // (4) Register events. Onreadystatechange event, which is called when the state changes. // We need to manually write some judgment logic if we want to call it when the full data request comes back. xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log(xhr.response); }else{ console.log(xhr.status); } } xhr.abort();Copy the code
Ref: blog.csdn.net/chaopingyao…
- Uninitialized state. When the XMLHttpRequest object is created, it is uninitialized and the readyState property value is 0.
- Initialization status. When the HTTP request is created using the open() method after the XMLHttpRequest object is created, the readyState property value is 1.
- Sending data status. When you use the send() method to send data after initializing the XMLHttpRequest object, the object is in the sending state and the readyState property value is 2.
- Received data status. After receiving and processing the data, the server sends the returned results to the client. At this point, the XMLHttpRequest object is in the receiving state and the readyState property value is 3.
- Completed state. After the XMLHttpRequest object receives the data, it enters the completed state and the readyState property value is 4. The received data is stored in the memory of the client computer and can be retrieved using the responseText or responseXml property
2. jQuery
JQuery encapsulates the Ajax request interface for us. In jQuery, the Ajax request is also cancelled by calling the.abort() method, except that the object is no longer a native XHR object
var jq = $.ajax({ type:"get", url:"https://api.github.com/", dataType:"json", success:function(data){ console.log(data); }, error:function(err){ console.log(err); } }) jq.abort();Copy the code
3. axios
If you use a framework like VUE a lot, you’ll use AXIos to send Ajax requests. Cancelling the Ajax request in AXIos differs from the above two forms, in which the request is cancelled through the axios.canceltoken.source () method
var CancelToken = axios.CancelToken; var source = CancelToken.source(); Axios ({method:"GET", url:"https://api.github.com/", cancelToken:source.token Identifies ajax operations controlled by source that will be cancelled}). Then ((res) => {console.log(res.data); }).catch((err) => { console.log(err); }); source.cancel('Operation canceled by the user.');Copy the code
Copy the code