重复出现故障的XHR

Repeat failed XHR

本文关键字:XHR 故障      更新时间:2023-09-26

是否有任何常见的方法、示例或代码模板来重复由于连接问题而失败的XHR?最好是在jQuery中,但也欢迎其他想法。

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

以下是我的操作方法:

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变量。不过,这一切都会发生在服务器端。

当然,不需要对重试次数进行限制。

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文档。