如何取消ajax请求,然后使用新参数再次调用?使用我的代码,之前的ajax请求仍然存在。
var stats_url = '/stats';
var live_stats_ajax_object = $.ajax();
$(".check-round").on("click", function(){
live_stats_ajax_object.abort();
round = $(this).attr('class').split(' ')[0];
get_live_stats(round);
});
var get_live_stats = function(round) {
live_stats_ajax_object = $.ajax({
url: stats_url,
type: "GET",
data: 'live_stats=true' + "&event_id=" + $( "#event-list option:selected" ).val()
+ "&fight_id=" + $( 'input[name=fightlist]:checked' ).val()
+ "&round=" + round,
dataType: "json",
timeout: 3500,
complete: function(xhr, textStatus) {
console.log("polling again stats for " + round);
if (textStatus != "abort") {
setTimeout( function() { get_live_stats(round); }, 10000 );
}
},
success: function(data) {
console.log("polling and got live stats for " + round);
console.log(data);
}
})
.fail(function() {
console.log("polling failed and couldn't get live stats for " + round);
})
};
我已经在这几个小时了。感谢
答案 0 :(得分:0)
修改,更新
尝试
// create empty object
var live_stats_ajax_object = {}
// reference for `setTimeout` within `get_live_stats`
, id = null
, stats_url = "/stats"
, get_live_stats = function (round) {
var eventlist = $( "#event-list option:selected" ).val()
, fightlist = $( 'input[name=fightlist]:checked' ).val();
live_stats_ajax_object = $.ajax({
type: "GET",
url: stats_url,
data: "live_stats=true&event_id="
+ eventlist
+ "&fight_id="
+ fightlist
+ "&round="
+ round,
timeout: 3500
});
// return `live_stats_ajax_object`
return live_stats_ajax_object
.done(function (data, textStatus, jqxhr) {
console.log("polling and got live stats for " + round + "\n"
, data);
})
.fail(function (jqxhr, textStatus, errorThrown) {
console.log("polling failed and couldn't get live stats for "
+ round);
})
.always(function (jqxhr, textStatus) {
if (textStatus !== "abort") {
// set `id` to `setTimeout`'s `numerical ID`
// call `get_live_stats()` within `setTimeout`
id = setTimeout(function () {
get_live_stats(round);
}, 10000);
}
});
};
$(".check-round").on("click", function () {
var round = $(this).attr('class').split(" ")[0];
// at initial click `live_stats_ajax_object` is empty object ,
// not having `jqxhr` `promise` property ;
// call `get_live_stats()` , which sets `live_stats_ajax_object`
// to `$.ajax()` , having `state` property at returned `jqxhr` object
if (!live_stats_ajax_object.hasOwnProperty("state")) {
get_live_stats(round);
} else {
// if `id` was set during initial call to `get_live_stats()`
if (id) {
// `.abort()` previous `live_stats_ajax_object` request ,
// `clearTimeout()` of `id` , set `id` to `null`
// call `get_live_stats()` with current `round` argument
live_stats_ajax_object.abort();
clearTimeout(id);
id = null;
get_live_stats(round);
}
}
});