超时XMLHttpRequest

Inv*_*tax 33 timeout xmlhttprequest

如何在以下脚本中添加超时?我希望它将文本显示为"超时".

var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""

function ajaxpage(url, containerid) {
    var page_request = false
    if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject) { // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (e) {
            try {
                page_request = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (e) {}
        }
    } else
        return false
    document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>'
    page_request.onreadystatechange = function () {
        loadpage(page_request, containerid)
    }
    if (bustcachevar) //if bust caching of external page
        bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
    page_request.open('GET', url + bustcacheparameter, true)
    page_request.send(null)
}


function loadpage(page_request, containerid) {
    if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
        document.getElementById(containerid).innerHTML = page_request.responseText
    else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1))
        document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments'
}
Run Code Online (Sandbox Code Playgroud)

小智 86

例如,使用XMLHttpRequest对象的超时属性.

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        alert("ready state = 4");
    }
};

xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);
Run Code Online (Sandbox Code Playgroud)

以上代码适合我!

干杯

  • 对于其他人看到XHR和IE10的间歇性错误,只需注意 - 必须在xhr.open语句之后设置xhr.timeout值.如果在我看到IE10间歇性地抛出错误之前设置了超时值. (12认同)
  • 请注意,在触发readyState == 4之后,ontimeout事件才会被触发.这不仅非直观,而且由于存在超时的原因而导致上传未成功,因此很难创建条件行为.例如,自定义用户警报以了解上载失败的原因.在我的情况下,我发现我只能用setTimeout完成我想要的东西.此外,截至2016年,xhr.timeout似乎无法在Safari上运行 (4认同)