确定是否$就错误是超时 [英] Determine if $.ajax error is a timeout

查看:206
本文介绍了确定是否$就错误是超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的魔法 jQuery.ajax(设置)

不过,我想知道是否有人曾与超时设置多少?

However, I'm wondering if anyone has played with the timeout setting much?

我知道这基本上是口述的本地时间的​​要求,但如果达到超时可以在触发什么?或者它只是停止监听回应?

I know it's basically for dictating the local time for a request, but can it trigger anything if the timeout is reached? Or does it simply stop listening for a response?

读jQuery的网站,我可以看到有没有传递的参数,所以它看起来像一个功能简单的设置。这是罚款。

Reading the jQuery site, I can see there are no arguments passed, so it seems like a simple setting with one capability. Which is fine.

不过,我想如果超时达到触发警报或某些功能。我可以看到,错误设置不会被触发,在这种情况

But, I'd like to trigger an alert or some function if the timeout is reached. I can see that the error setting doesn't get triggered, in this case.

下面是我的代码段:

$("form#testform").submit(function(){ 

 var allFormValues = $("form#testform").serialize(); 

   $.ajax({
    cache:false,
    timeout:8000,  // I chose 8 secs for kicks
    type:"POST",
    url:"someurl.php",
    data:allFormValues,
    error:function(){ alert("some error occurred") },
    success:function(response){ alert(response); }
   });

});

有谁知道如何与超时工作的更多?

Does anyone know how to work more with timeout?

推荐答案

如果你的错误事件处理程序需要三个参数(xmlhtt prequest,textstatus和消息)时发生超时,状态ARG将是'超时。

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

按照 jQuery的文档

第二个可能的值   参数(除了空)是超时,   错误,notmodified和   parsererror。

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

您可以处理你的错误据此即可。

You can handle your error accordingly then.

我创造了这个提琴演示这一点。

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});​

使用的jsfiddle,可以测试Ajax调用 - 它会间隔2秒响应之前。我把超时1秒的设置,所以它应该出错误,并传回超时的textstatus的错误处理程序。

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

希望这有助于!

这篇关于确定是否$就错误是超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆