XMLHttpRequest 取消請求


一,xmlHttpRequest介紹

是一個前后端數據通信的對象,在不刷新頁面的情況下進行數據通信,在頁面加載完成后請求后台服務、接收后台數據。

創建 XMLHttpRequest 對象:

xhr = new XMLHttpRequest();

xhr = new ActiveXObject("Microsoft.XMLHTTP");

創建請求

xhr.open(method, url, async);

xhr.send(string);

在使用post請求時string可選填。

請求響應

xhr.responseText; 獲取字符串形式響應數據

xhr.responseXML; 獲取 XML形式的響應數據

readyState請求響應階段

xhr.onreadystatechange = function(){

xhr.readyState === 4; // Done 請求完成

xhr.status === 200; // 請求返回成功

}

xhr 對象提供的 API

  1. 0: "UNSENT"  請求未初始化
  2. 1: "OPENED"  請求連接已經建立
  3. 2: "HEADERS_RECEIVED"  請求已經接收
  4. 3: "LOADING"  請求處理中
  5. 4: "DONE"      請求已完成,響應已就緒
  6. 5: "onreadystatechange"
  7. 6: "readyState"
  8. 7: "timeout"
  9. 8: "withCredentials"
  10. 9: "upload"
  11. 10: "responseURL"
  12. 11: "status"
  13. 12: "statusText"
  14. 13: "responseType"
  15. 14: "response"
  16. 15: "responseText"
  17. 16: "responseXML"
  18. 17: "open"
  19. 18: "setRequestHeader"
  20. 19: "send"
  21. 20: "abort"  中止請求
  22. 21: "getResponseHeader"
  23. 22: "getAllResponseHeaders"
  24. 23: "overrideMimeType"

 

二,如何取消 ajax請求

上述簡介可以看出在使用xhr進行異步的請求,是可以進行中止的。

 

方法一:xhr.abort() 調用中止api

xhr 就是 XMLHttpRequest 的實例,該實例調用對應的xhr.abort() 會終止當前的請求。

var xhr = new XMLHttpRequest(); xhr.open('get', 'https://jianshu.com', true); xhr.send(); xhr.onreadystatechange= function (){ console.log(xhr.responseText, '-- respone') } setTimeout(() => {xhr.abort()}, 20);

 

方法二:AbortController

var controller = new AbortController(); var signal = controller.signal; var d = fetch('www.jianshu.com',{signal}).then(d => {console.log(d)}).catch(err => {console.log(err, 'baocuo...')}) setTimeout(() => {controller.abort()}, 10);
// DOMException: The user aborted a request. "baocuo..."

 

方法三:axios.CancelToken

axios.CancelToken 

axios對abort方法進行了封裝,取消請求

1,axios請求的第二個參數對象中增加一個key,cancelToken,cancelToken是 CancelToken的實例

2,實例的傳參是一個函數,函數的參數是取消請求的方法

3,將這個方法透傳到外層,可以在請求完成之前,隨時取消請求。

 

 

三,ajax請求的攔截器原理

https://www.jianshu.com/p/115b4c79a75d 

https://www.jianshu.com/p/22b49e6ad819


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM