是否有常见的方法、示例或代码模板可用于重复由于连接问题而失败的XHR请求?最好使用jQuery,但其他想法也可以。
我需要将一些应用程序状态数据发送到数据库服务器。这是由用户点击按钮发起的。如果XHR由于某种原因失败,我需要确保稍后(无需交互)以正确的顺序发送数据(用户可能会再次按下按钮)。
是否有常见的方法、示例或代码模板可用于重复由于连接问题而失败的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");
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文档以获取更多信息。