2015-01-15 188 views
2

好了,所以我可以访问使用从HTTP标头响应获取日期

xhr.getAllResponseHeaders(); 

的HTTP Ajax响应头,但它似乎并没有得到它的日期,但它的存在:

[Chrome] 
**Response Header** 
Access-Control-Allow-Origin:* 
Cache-Control:no-cache 
Content-Length:8092 
Content-Type:application/json; charset=utf-8 
**Date:Thu, 15 Jan 2015 16:30:13 GMT** 
Expires:-1 
Pragma:no-cache 
Server:Microsoft-IIS/8.0 
TotalCount:116 
X-AspNet-Version:4.0.30319 
X-Powered-By:ASP.NET 

和代码只能说明这一点:

[output on alert xhr.getAllResponseHeaders();] 

Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 

这里的Ajax调用:

$.ajax({ 
     url: url, 
     type: "GET", 
     contentType: "application/json;charset=utf-8", 
     async: true, 
     success: function (data,status, xhr) { 

     displayNewData(data); 
     alert(xhr.getAllResponseHeaders()); 

    }, 
    error: function() { 
    alert(url); 

    } 
}); 

有没有一种方法可以在响应头中获取日期?

回答

2

这有助于:

var req = new XMLHttpRequest(); 
req.open('GET', document.location, false); 
req.send(null); 
var headers = req.getAllResponseHeaders().toLowerCase(); 
alert(headers); 

Accessing the web page's HTTP Headers in JavaScript

+0

它不会工作,因为你不能访问日期字段使用'getAllResponseHeaders'或'getResponseHeader()' Chrome抛出一个错误“拒绝获取不安全的标题”日期”' – stefbach 2015-09-30 05:33:26

0
在你的成功方法

success: function (data,status, xhr) { 

    console.log(xhr.getResponseHeader('Date')); 


}, 

如果响应是成功的

res=xhr.getResponseHeader('Date'); 

如果响应失败

res=data.getResponseHeader('Date'); 
+0

我需要得到这似乎是在响应头 – EnderCode 2015-01-15 16:45:21

+0

-_-严重... – EnderCode 2015-01-15 17:04:34

+0

检查什么服务器的当前时间,你没有回答我的问题,并且你删除了你的评论,告诉我给一个javascript函数的String类型的参数。我希望我可以投票给你。 – EnderCode 2015-01-15 18:38:53

3

可能出现这种情况,您正在发出CORS请求,并且出于安全原因过滤掉了标头。

另请参见关于missing response headers in ajax request的相似问题。 的解决方案可能是设置此HTTP标头在服务器响应:

Access-Control-Expose-Headers: Date