超时 XMLHttpRequest [英] Timeout XMLHttpRequest

查看:36
本文介绍了超时 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I add a timeout to the following script? I want it to display text as "Timed Out".

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'
}

推荐答案

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

using the timeout properties of XMLHttpRequest object for example.

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);

上面的代码对我有用!

干杯

这篇关于超时 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆