有什麼常見的方法,示例或代碼模板如何重複由於連接問題而失敗的XHR? 最好在jQuery中,但歡迎其他想法。重複失敗XHR
我需要發送一些應用程序狀態數據到數據庫服務器。這是由用戶點擊一個按鈕啓動的。如果XHR出於某種原因失敗,我需要確保數據以正確的順序在晚些時候發送(這裏不需要交互)(用戶可以再次按下按鈕)。
有什麼常見的方法,示例或代碼模板如何重複由於連接問題而失敗的XHR? 最好在jQuery中,但歡迎其他想法。重複失敗XHR
我需要發送一些應用程序狀態數據到數據庫服務器。這是由用戶點擊一個按鈕啓動的。如果XHR出於某種原因失敗,我需要確保數據以正確的順序在晚些時候發送(這裏不需要交互)(用戶可以再次按下按鈕)。
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。
這是我會怎麼做:
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");
要確保一切都在正確的順序發送,你可以在某些ID變量的send
功能釘。儘管如此,這將全部發生在服務器端。
當然,不需要對重試進行限制。