异步获取日期标题

时间:2016-02-24 12:28:07

标签: javascript

正如标题所说,我想获得响应标题日期值,但我一直收到以下警告:

  

主线程上的同步XMLHttpRequest因不推荐使用   它对最终用户的体验产生不利影响。如需更多帮助,   检查https://xhr.spec.whatwg.org/

我的代码:

function getxmlhttp () {
    // although IE supports the XMLHttpRequest object, but it does not work on local files.
    var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
    if (window.XMLHttpRequest && !forceActiveX) {
        return new XMLHttpRequest();
    }else {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {}
    }
    alert ("Your browser doesn't support XML handling!");
    return null;
};

function srvTime(){
    xmlHttp = getxmlhttp();
    //xmlHttp.open('HEAD',window.location.href.toString(),false);
    //need to send this to a non-volitile page
    xmlHttp.open('GET',"blank.php",false);
    xmlHttp.setRequestHeader("Content-Type", "text/html");
    xmlHttp.send(null);
    console.log("raw " + xmlHttp.getResponseHeader("Date"));
    return xmlHttp.getResponseHeader("Date");
};

当我切换这一行时:

xmlHttp.open('GET',"blank.php",true);

说实话,该值返回NULL

那么可以这样做,还是我必须在控制台中接受警告?

谢谢

1 个答案:

答案 0 :(得分:0)

正如您的标题所述,您必须异步发出请求。这意味着您必须发出请求并等待它完成以获取信息。这样的事情应该有效:

function srvTime(callback) {
    xmlHttp = getxmlhttp();
    //xmlHttp.open('HEAD',window.location.href.toString(),false);
    //need to send this to a non-volitile page
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) { // The operation is complete
            console.log("raw " + xmlHttp.getResponseHeader("Date"));
            callback(xmlHttp.getResponseHeader("Date"));
            xmlHttp = null;
        }
    };
    xmlHttp.open('GET', "blank.php", true);
    xmlHttp.setRequestHeader("Content-Type", "text/html");
    xmlHttp.send(null);
};

请注意,您必须更改srvTime方法的签名。您无法从中返回数据,调用者必须提供一个回调函数,该函数会在请求完成后接收日期。

如何将此函数与新签名一起使用的示例如下:

srvTime(function (serverDate) {
    document.getElementById("clock").innerHTML = "Game Time: " + serverDate;
});