2016-02-24 37 views
0

正如标题所说,我想要得到的响应头日期的价值,但我不断收到以下警告:获取日期标题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); 

是真实的,值返回NULL

所以可以这样做,还是我必须在控制台中生存警告?

谢谢

+0

是jQuery的选项吗?如果是,那么看到这个答案。 http://stackoverflow.com/a/1457708/1437261 – Gogol

+0

你是否将脚本标记中包含的脚本从blank.php返回给客户端? – dreamweiver

+1

您需要使用带有异步请求的onreadystatechange/load处理程序,然后才能使用数据/头文件。见https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Get_last_modified_date –

回答

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

他只想要一个标题,所以HEAD可能是一个更好的动词。 –

+0

@AlexK。是的,这是真的。为了澄清,我的意图是修改他现有的代码就够了。不过,现在你提到它了,你应该能够在'readyState == 2'(头部收到)处获得头部,这将是另一个优化。 –

+0

@JackA。好,所以我不明白的是“回调”。你能否解释或指导我解释如何从那里获取信息的地方?感谢您的帮助! – KeeganS