如何通过按钮或点击事件取消/中止/停止我尚未收到响应的所有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);
}
});
});
}
答案 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