异步获取日期标头
Get Date Header Asyncronously
正如标题所说,我想获取响应标头日期值,但我不断收到以下警告:
主线程上的同步 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;
});
相关文章:
- 如何从Angularjs中的新日期获取日期格式
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 从javascript中的日期获取月份号
- 从datetimepicker引导程序上点击的日期获取点击事件
- 如何在JS中从Y-m-d日期获取unix时间戳
- 从getTime()类型的日期获取日期和时间,以显示mySQL数据库中的日期
- 使用 Jquery 从日期获取星期几
- 如何在没有周末的情况下添加天数以从当前日期获取下一个日期
- 从服务器返回的日期获取星期几
- 如何使用 momentjs 从日期获取日期名称
- 时刻.js从日期获取日期名称
- 突出显示:在向下钻取之前获取事件
- 试图从X射线抓取中获取信息
- 我想在 JavaScript 中使用日期函数将日期获取为 9 月 8 日星期日上午 11:46
- 从当前日期获取GMT字符串
- jQuery:抓取日期&来自网页的时间数据
- 为什么angularjs摘要使用日期获取函数进入无限循环
- 从格式化日期获取UTC时间戳-javascript
- 在github和eclipse中,导入、推送、拉取和获取意味着什么
- 如何在codebehind中为Datepicker设置日期/获取日期