admin管理员组

文章数量:1334826

Is there any mon way, example or code template how to repeat a XHR that failed due to connection problems? Preferably in jQuery but other ideas are wele.

I need to send some application state data to a database server. This is initiated by the user clicking a button. If the XHR fails for some reason I need to make sure that the data is sent later (no interaction needed here) in the correct order (the user may press the button again).

Is there any mon way, example or code template how to repeat a XHR that failed due to connection problems? Preferably in jQuery but other ideas are wele.

I need to send some application state data to a database server. This is initiated by the user clicking a button. If the XHR fails for some reason I need to make sure that the data is sent later (no interaction needed here) in the correct order (the user may press the button again).

Share Improve this question asked Jan 25, 2012 at 15:12 Mq_Mq_ 2373 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Here's how I would do it:

function send(address, data) {

    var retries = 5;

    function makeReq() {


        if(address == null)
            throw "Error: File not defined."

        var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");

        if(req == null)
            throw "Error: XMLHttpRequest failed to initiate.";

        req.onload = function() {
            //Everything's peachy
            console.log("Success!");
        }
        req.onerror = function() {
            retries--;
            if(retries > 0) {
                console.log("Retrying...");
                setTimeout(function(){makeReq()}, 1000);
            } else {
                //I tried and I tried, but it just wouldn't work!
                console.log("No go Joe");
            }
        }

        try {
            req.open("POST", address, true);
            req.send(data); //Send whatever here

        } catch(e) {
            throw "Error retrieving data file. Some browsers only accept cross-domain request with HTTP.";
        }


    }
    makeReq();

}


send("somefile.php", "data");

To make sure everything is sent in the right order, you could tack on some ID variables to the send function. This would all happen server-side though.

And of course, there doesn't need to be a limit on retries.

jQuery provides an error callback in .ajax for this:

$.ajax({
    url: 'your/url/here.php',
    error: function(xhr, status, error) {
        //  The status returns a string, and error is the server error response.
        //  You want to check if there was a timeout:
        if(status == 'timeout') {
           $.ajax();
        }
    }
});

See the jQuery docs for more info.

本文标签: javascriptRepeat failed XHRStack Overflow