是否有可能在jQuery.post()上检查超时?
我有这个代码从mysql DB请求一些文件夹信息:
function gotoDir(pmcat_id, pcat_id){ $('#slideshowContainer').html(''); $.post("/publish/includes/content.includes/functions.slideshow.php", { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id }, function(data){ $('#pageSlideshow').html(data.content); }, "json" ); }
有时,由于互联网连接不良,post请求超时。 是否可以在$ .post()上设置超时检查? 例如:如果$ .post()使用多于X ms,则重新加载请求。
更新:看起来我找到了一个解决方案:
function gotoDir(pmcat_id, pcat_id){ $('#slideshowContainer').html(''); $.ajax({ type:"post", url:"/publish/includes/content.includes/functions.slideshow.php", data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id }, dataType: "json", success:function(data) { if (data == null){ alert('ajax failed. reloading...'); gotoDir(pmcat_id, pcat_id); } else { $('#pageSlideshow').html(data.content); } } }); }
这是一个可行的方法吗? :S
$ .ajax具有完成所要求的所有function:
function gotoDir(pmcat_id, pcat_id) { $('#slideshowContainer').html(''); $.ajax({ type: "POST", url: "/publish/includes/content.includes/functions.slideshow.php", data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id }, dataType: "json", timeout: 500, // in milliseconds success: function(data) { // process data here }, error: function(request, status, err) { if(status == "timeout") { gotoDir(pmcat_id, pcat_id); } } }); }
请注意,除非要在要设置的特定时间后触发错误方法,否则无需设置超时选项。
您应该使用$.ajax()
和$.ajaxError()
,然后使用“ajaxComplete”,您可以检查您的请求是否timedout
或succeded
。
来源: jQuery API