如何使用jQuery AJAX请求访问ETag标头?

时间:2014-01-24 20:34:44

标签: javascript jquery ajax http-headers etag

我正在使用jQuery ajax调用来从正在HTTP响应头中发送ETag的服务器请求数据。我需要访问标头,但是当请求成功并且我调用jqXHR.getAllResponseHeaders()时,我只看到服务器返回的标头的子集。

示例:

var jqXHR = $.ajax({
        type: 'GET',
        url: <my api url>,
        dataType: 'json',
        ifModified: true,
        success: function (result) {
          var headers = jqXHR.getAllResponseHeaders();
          console.log(JSON.stringify(headers));
        });

我从jqxhr看到的标题是:

Pragma: no-cache\r\n
Last-Modified: Wed, 22 Jan 2014 10:45:14 +0000\r\n
Content-Type: text/html\r\n
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, no-cache=\"set-cookie\"\r\n
Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n

从服务器返回的实际标头(在chrome dev工具中观察到):

Access-Control-Allow-Origin:*
Cache-Control:no-cache="set-cookie"
Cache-Control:post-check=0, pre-check=0
Cache-Control:no-store, no-cache, must-revalidate
Connection:keep-alive
Content-Encoding:gzip
Content-Length:407
Content-Type:text/html
Date:Fri, 24 Jan 2014 20:27:54 GMT
ETag:"29d8d1d98115057fe902b520199ea1b3"
Expires:Sat, 26 Jul 1997 05:00:00 GMT
Last-Modified:Thu, 23 Jan 2014 07:14:57 +0000
Pragma:no-cache
Server:nginx/1.1.19
Set-Cookie:AWSELB=F3E9557318EB956CA386FC6CB4270164AD7830493699A2B6AED008F4C5F9DB5952A2A1072C33DDC32DEDE0CA6A3734EBAFD51B57A7A093B69A36A6659EF493E1B92BA63DE6;PATH=/
X-Powered-By:PHP/5.4.19

我需要访问ETag标头,但似乎jQuery或chrome正在隐藏它。我在Firefox中尝试了相同的代码,结果相同。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:4)

您可以尝试在完整回调中访问标头而不是成功

complete: function(XMLHttpRequest, textStatus){
   var eTag = XMLHttpRequest.getResponseHeader('ETag');
}

这似乎适用于某些用户here

答案 1 :(得分:1)

这可能是一个CORS问题。我遇到了同样的问题,我在Chrome中看到了标题 - 但是我的代码无法访问它。

我的后端有ASP.Net Web API,<system.webServer>节点下必须添加:

<httpProtocol>
    <customHeaders>
          <add name="Access-Control-Expose-Headers" value="ETag, Retry-After"/>
    </customHeaders>
</httpProtocol>

我在阅读以下帖子后意识到这一点: Etag header not returned from jQuery.ajax() cross-origin XHR