XMLHTTPRequest脚本中没有internet连接和超时

No internet connection and timeout in XMLHTTPRequest Script

本文关键字:连接 超时 internet 脚本 XMLHTTPRequest      更新时间:2023-09-26

我的web应用的许多函数上都有这段代码

function ui_editlocation(id){
var hr   = new XMLHttpRequest();
var url  = "scripts/ui_processing.php";
var ui   = "editlocation";
var vars = "ui="+ui+"&id="+id;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("ui_content").innerHTML = return_data;
    }
}
hr.send(vars);
document.getElementById("ui_content").innerHTML = "Loading...";
}

我想添加一些代码,如果互联网连接中断,你会收到一条消息,上面写着"请检查你的互联网连接,单击此处重试"

此外,如果有互联网连接,我希望它在30秒后超时,并说"我们目前的网络需求很高,请单击此处重试"

我需要"单击此处重试"来重新发送请求

我知道这是一个很大的要求,但任何帮助都将不胜感激。

谢谢Carl

function ui_editlocation(id){
var hr   = new XMLHttpRequest();
var timeout=setTimeout(function(){
    hr.abort();
    timeout=null;
    if(confirm("Do you want to try again?")){ui_editlocation(id);}
},30000);
var url  = "scripts/ui_processing.php";
var ui   = "editlocation";
var vars = "ui="+ui+"&id="+id;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        if(timeout){cancelTimeout(timeout);timeout=null;}
        var return_data = hr.responseText;
        document.getElementById("ui_content").innerHTML = return_data;
    }
}
hr.send(vars);
document.getElementById("ui_content").innerHTML = "Loading...";
}