取消Javascript異步請求

普通的ajax很少會涉及到需要取消請求的操作,但是在定時(setInterval)發(fā)送異步請求的時候,或者頻繁切換數(shù)據(jù)時候,取消ajax就變得額外重要,這時候就需要取消之前未完成的請求.

1.jquery取消異步請求

   var xhr;
   var ajax = function () {
       if (xhr && xhr.readyState != 4) {
           xhr.abort();
       }
       xhr = $.ajax({
           url: 'http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData',
           success: function (data) {
               //do something
           }
       });
   };
   //輪詢請求,,如果上一次請求未完成,則取消上次請求
   setInterval(ajax, 2000);

2.axios取消異步請求

同時發(fā)送兩次請求,取消其中一個
如果同時取消,可以使用同一個source.token

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    
    <button id="a">停止</button>
    <script type="text/javascript">
        var CancelToken = axios.CancelToken;
        var source = CancelToken.source();
        
        axios.get("http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData", {
          cancelToken: source.token
        }).catch(function(thrown) {
          if (axios.isCancel(thrown)) {
            //取消操作
            console.log('Request canceled', thrown.message);
          } else {
            //處理異常
          }
        });
        
        
        var source2 = CancelToken.source();
        axios.get("http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData", {
          cancelToken: source2.token
        }).catch(function(thrown) {
          if (axios.isCancel(thrown)) {
            //取消操作
            console.log('Request canceled', thrown.message);
          } else {
            //處理異常
          }
        });
        
        $('#a').click(function(){
            
                source.cancel('Operation canceled by the user.');
        })
    </script>
</body>
</html>
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容