重复失败的XHR请求

6

是否有常见的方法、示例或代码模板可用于重复由于连接问题而失败的XHR请求?最好使用jQuery,但其他想法也可以。

我需要将一些应用程序状态数据发送到数据库服务器。这是由用户点击按钮发起的。如果XHR由于某种原因失败,我需要确保稍后(无需交互)以正确的顺序发送数据(用户可能会再次按下按钮)。

2个回答

4
这是我会做的方法:
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");

为了确保所有内容都按正确顺序发送,你可以在“send”函数中添加一些ID变量。但这些操作均需在服务器端执行。
当然,重试次数也没有必要限制。

1

jQuery在.ajax中提供了一个错误回调函数:

$.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();
        }
    }
});

查看jQuery文档以获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接