我正在尝试对从表中读取并显示数据的函数进行ajax调用,但是如果该过程花费的时间太长,则ajax调用应停止并显示错误消息。我已经尝试过在ajax函数上使用timeout
参数,但是不会触发错误处理程序;而是调用成功事件处理程序。
JS:
var start_time = new Date().getTime();
var req_time, max_time;
max_time = 100;
$.ajax({
type: 'get',
url: 'mypage/myfunction',
dataType: 'json',
async: true,
timeout: max_time,
success: function(res) {
req_time = new Date().getTime() - start_time; // 2106 miliseconds
console.log('success!', res, req_time);
},
error: function(err, txtStatus) {
console.log('error!', err, txtStatus); // doesn't get triggered even though req_time > max_time
},
complete: function() {
req_time = new Date().getTime() - start_time; // 2107 miliseconds
console.log('complete', req_time);
}
});
最佳答案
请注意,超时时间以毫秒为单位。因此,如果您想执行错误处理程序,请将max_value分配给附近的2000!
jQuery
var start_time = new Date().getTime();
var req_time, max_time;
max_time = 2000; // Please update the max_time
$.ajax({
type: 'get',
url: 'mypage/myfunction',
dataType: 'json',
async: true,
timeout: max_time,
success: function(res) {
req_time = new Date().getTime() - start_time; // 2106 miliseconds
console.log('success!', res, req_time);
},
error: function(err, txtStatus) {
console.log('error!', err, txtStatus); // doesn't get triggered even though req_time > max_time
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
},
complete: function() {
req_time = new Date().getTime() - start_time; // 2107 miliseconds
console.log('complete', req_time);
}
});
jQuery 1.8+ var start_time = new Date().getTime();
var req_time, max_time;
max_time = 2000; // Please update the max_time
$.ajax({
type: 'get',
url: 'mypage/myfunction',
dataType: 'json',
async: true,
timeout: max_time,
}).done(function(){
//do something
}).fail(function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
});
关于jquery - ajax获取请求超时未触发错误处理程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62888344/