getJSON超时处理
我正在使用jQuery getJSON()
函数。 这个函数获取数据没有问题。 但有时候等待,等待等待……我的加载栏显示加载加载在页面中心。 所以jQuery ajax()
函数有一个超时变量。 但我想使用getJSON
函数。 我认为我可以使用ajaxStart()
和ajaxStop()
函数。 但是怎么样?
$('.loadingDiv') .hide() .ajaxStart(function() { $(this).fadeIn(); setTimeout("throw '';",15000) //i used this but didn't work setTimeout("return;",15000) //i used this but didn't work setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events) }) .ajaxStop(function() { $(this).fadeOut(); });
getJSON()
返回一个可以调用abort
函数的promise:
var p = $.getJSON(..., function(){ alert('success');}); setTimeout(function(){ p.abort(); }, 2000);
编辑:但如果你的目标只是在需要花费太多时间的时候中止,那么致命吉他的答案会更好。
getJSON()
只是以下的简写:
$.ajax({ dataType: "json", url: url, data: data, success: success });
所以你可以使用$.ajax()
并根据需要指定timeout
选项。 另见: http : //api.jquery.com/jQuery.getJSON/
正如致命吉他提到的getJSON()
函数只是$.ajax()
的简写。 如果要检测是否发生了超时而不是实际错误,请使用下面的代码。
var request = $.ajax({ dataType: "json", url: url, data: data, success: function( ) { }, timeout: 2000 }).fail( function( xhr, status ) { if( status == "timeout" ) { // do stuff in case of timeout } });
总有核路线:
//Set AJAX timeout to 10 seconds $.ajaxSetup({ timeout: 10*1000 });
这将设置您的程序所做的所有AJAX请求(甚至通过$ .getJSON),以获得超过10秒的时间(或者你有什么)。
setTimeout函数在全局范围内指定数量的milisecons之后执行一组代码。
getJSON函数(根据jQuery文档http://api.jquery.com/jQuery.getJSON/ )是以下的简写:
$.ajax({ dataType: "json", url: url, data: data, success: success });
所以你想要这样打电话:
$.ajax({ dataType: "json", url: url, data: data, success: success, timeout: 15000 }); $('.loadingDiv') .hide() .ajaxStart(function() { $(this).fadeIn(); }) .ajaxStop(function() { $(this).fadeOut(); });
我不认为这些答案中的任何一个都是理想的。 我知道这已经晚了很多年,但你想要做的是使用.ajax();
的成功/错误回调选项.ajax();
接收JSONP响应时的方法。
我将如何构造这个示例:
// Call $.ajax({ // URL you want to get url: 'http://example.com/json?callback=?', // Set a realistic time in milliseconds timeout: 3000, // Put in success callback function here, this example // shows you the data you got back from the call success: function(data) { console.log(data); }, // Put in an error handling function, just an alert in this case error: function(badData) { alert('The call was unsuccessful'); }, type: 'POST' });