【问题标题】:Getting Date from http header response从 http 标头响应中获取日期
【发布时间】:2015-03-14 03:18:05
【问题描述】:

好的,我可以使用

访问 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);

    }
});

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

【问题讨论】:

    标签: javascript jquery ajax http-headers


    【解决方案1】:

    可能是您发出CORS 请求并且出于安全原因过滤了标头。

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

    Access-Control-Expose-Headers: Date
    

    【讨论】:

      【解决方案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

      【讨论】:

      • 它不起作用,因为您无法使用 'getAllResponseHeaders' 或 'getResponseHeader()' 访问日期字段 Chrome 会抛出错误 'Refused to get unsafe header "date"'
      【解决方案3】:

      在你的成功方法中:

       success: function (data,status, xhr) {
      
          console.log(xhr.getResponseHeader('Date'));
      
      
      },
      

      如果响应成功

      res=xhr.getResponseHeader('Date');
      

      如果响应失败

      res=data.getResponseHeader('Date');
      

      【讨论】:

      • 我需要获取似乎在响应头中的服务器的当前时间
      • 什么都不做,你没有回答我的问题,你删除了你的评论告诉我给一个 javascript 函数类型为 String 的参数。我希望我能投票给你。
      • 是的,我在发布问题之前已经尝试过了,它给出了 null,显然是因为它不会得到我在问题中提到的细节之外的其他细节......
      • 如果我的问题不值得投票,你就不应该投票。如果你想表现得很好,谢谢。
      • 我清楚地看到响应中的日期字段。你说的是哪一个?否则,只需从服务器获取时间作为 json 数据响应的一部分
      【解决方案4】:

      如果您使用的是 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,它会显示“日期”。

      【讨论】:

        猜你喜欢
        • 2017-11-06
        • 1970-01-01
        • 2014-02-26
        • 2016-09-21
        • 1970-01-01
        • 2020-09-04
        • 2015-10-18
        • 2016-04-25
        • 1970-01-01
        相关资源
        最近更新 更多