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

时间:2016-05-03 11:43:44

标签: javascript jquery ajax javascript-events

如何通过按钮或点击事件取消/中止/停止我尚未收到响应的所有AJAX请求/查询?因为我做了多个AJAX调用。这是我的代码:

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);
            }
        });
    });
}

1 个答案:

答案 0 :(得分:2)

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()

现在假设这是你的按钮:

<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