English 中文(简体)
Determine if $.ajax error is a timeout
原标题:

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?

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.

Here s my snippet:

$("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?

最佳回答

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

Per the jQuery documentation:

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

Hope this helps!

问题回答

暂无回答




相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签