繁体   English   中英

从http标头响应获取日期

[英]Getting Date from http header response

好的,因此我可以使用访问HTTP ajax响应标头

xhr.getAllResponseHeaders();

但似乎没有日期,尽管它在那里:

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

    }
});

有没有办法可以在响应头中获取日期?

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

另请参见有关ajax request中缺少响应标头的类似问题。 解决方案可能是在服务器响应中设置此HTTP标头:

Access-Control-Expose-Headers: Date

这有帮助:

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

使用JavaScript访问网页的HTTP标头

在您的成功方法中:

 success: function (data,status, xhr) {

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


},

如果回应成功

res=xhr.getResponseHeader('Date');

如果响应失败

res=data.getResponseHeader('Date');

如果您使用的是Nginx,则可以将以下代码放在Nginx配置文件中:

add_header 'Access-Control-Expose-Headers' 'Date';

对于实际的配置示例:

location / {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Expose-Headers' 'Date';
    root /usr/local/nginx/html;
    index  index.html index.htm;
}

重新启动nginx服务后,您可以再次调用getAllResponseHeaders,它将显示“日期”。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM