简体   繁体   English

jQuery在单击按钮时中止所有AJAX请求(查询)

[英]jQuery abort all AJAX requests(query) on click of a button

How can I cancel/abort/stop all AJAX requests/query that I have not yet received the response with button or some click event? 如何取消/中止/停止尚未收到带有按钮或单击事件的响应的所有AJAX请求/查询? Because I make multiple AJAX calls. 因为我打了多个AJAX电话。 Here is my code: 这是我的代码:

function makeCalls() {
    var urls = ["url1.php", "url2.php", "url3.php", "url4.php"];
    $.each(urls, function(index, value) {
        $.ajax({
            global: false,
            type: 'POST',
            url: value,
            dataType: 'html',
            data: returnData(),
            cache: false,
            timeout: 60000,
            success: function(result) {         
                switch(value) {
                    case "url1.php":
                        // my code for url1 
                    case "url2.php":
                        // my code for url2 
                    case "url3.php":
                        // my code for url3 
                    case "url4.php":
                        // my code for url4 
                }
            },
            error: function (request, status, error) {
                console.log('ERROR: ' + request.responseText);
            }
        });
    });
}
var ajaxRequestsArray = [];

function makeCalls() {
    var urls = ["url1.php", "url2.php", "url3.php", "url4.php"];
    $.each(urls, function(index, value) {
     var ajaxRequest = $.ajax({
            global: false,
            type: 'POST',
            url: value,
            dataType: 'html',
            data: returnData(),
            cache: false,
            timeout: 60000,
            success: function(result) {         
                switch(value) {
                    case "url1.php":
                        // my code for url1 
                    case "url2.php":
                        // my code for url2 
                    case "url3.php":
                        // my code for url3 
                    case "url4.php":
                        // my code for url4 
                }
            },
            error: function (request, status, error) {
                console.log('ERROR: ' + request.responseText);
            }
        });
       ajaxRequestsArray.push( ajaxRequest );
    });
}//makeCalls()

Now suppose this is your button: 现在假设这是您的按钮:

<a href="#" id="abort-all-ajax" title="Abort all requests">Abort all requests</a>

$("#abort-all-ajax").on("click", function(e){
    e.preventDefault();
    for(var i = 0; i < ajaxRequestsArray.length; i++ )
    {
      var curRequest = ajaxRequestsArray[i];
      curRequest.abort();
    }//for()

});//click handler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM