异步获取日期标头

Get Date Header Asyncronously

本文关键字:取日期 获取 异步      更新时间:2023-09-26

正如标题所说,我想获取响应标头日期值,但我不断收到以下警告:

主线程上的同步 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);

如果为 true,该值将返回 NULL

那么可以做到这一点,还是我必须忍受控制台中的警告?

谢谢

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

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