有没有什么通用的方法、示例或代码模板来重复由于连接问题而失败的XHR?最好是在jQuery中,但也欢迎其他想法。
我需要向数据库服务器发送一些应用程序状态数据。这是通过用户单击按钮来启动的。如果XHR由于某种原因失败,我需要确保稍后以正确的顺序发送数据(这里不需要交互)(用户可以再次按下按钮)。
发布于 2012-01-25 23:16:21
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();
}
}
});有关详细信息,请参阅the jQuery docs。
发布于 2012-01-25 23:31:10
下面是我会怎么做:
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变量。不过,这一切都会发生在服务器端。
当然,不需要限制重试次数。
https://stackoverflow.com/questions/9004996
复制相似问题