确定 $.ajax 错误是否超时

2022-01-30 00:00:00 jquery ajax connection-timeout

我正在利用 jQuery.ajax( settings ) 的魔力.

I'm utilizing the magic of jQuery.ajax( settings ).

但是,我想知道是否有人经常使用超时设置?

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?

推荐答案

如果您的错误事件处理程序在发生超时时采用三个参数(xmlhttprequest、textstatus 和 message),则状态参数将为超时".

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

根据 jQuery 文档:

第二个可能的值参数(除了 null)是超时",错误"、未修改"和解析器错误".

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

您可以相应地处理您的错误.

You can handle your error accordingly then.

我创建了这个 fiddle 来演示这一点.

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(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});​

使用 jsFiddle,您可以测试 ajax 调用——它会在响应前等待 2 秒.我将超时设置为 1 秒,因此它应该会出错并将超时"的文本状态返回给错误处理程序.

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.

希望这会有所帮助!

相关文章