如何在AJAX中获取响应头

时间:2015-12-23 06:09:17

标签: jquery ajax

我正在使用以下代码进行AJAX调用

 $.ajax({
        type: "POST",
        url: "http://******/cxf/view/*****",
        data: {*****},
        headers: {*****},
        success: function (dt, status, request) {
            console.log(request.getAllResponseHeaders());

        },
        error: function (jqXHR, status) {

        }
    });

这是仅打印内容类型。在开发人员控制台中,我可以看到响应中的标头数量。我怎样才能在AJAX中获得这些标题

enter image description here

3 个答案:

答案 0 :(得分:14)

这似乎没问题。我尝试过并且有效。

使用JSONPlaceholder,这是我的代码

$.ajax({
  url: root + '/posts/1',
  headers: {'test': 'test'},
  method: 'GET'
}).then(function(data, status, xhr) {
  console.log(xhr.getAllResponseHeaders());
});

结果是

Pragma: no-cache
Date: Wed, 23 Dec 2015 06:36:57 GMT
Via: 1.1 vegur
X-Content-Type-Options: nosniff
Server: Cowboy
X-Powered-By: Express
Vary: Origin
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Access-Control-Allow-Credentials: true
Content-Length: 292
Etag: W/"124-yv65LoT2uMHrpn06wNpAcQ"
Expires: -1

答案 1 :(得分:6)

在您的服务器上,您需要添加

res.header("Access-Control-Expose-Headers", "header-you-want-to-expose");

然后您就可以在浏览器中访问它了。

答案 2 :(得分:3)

我使用了您使用的相同代码

success: function (dt, status, request) {
            console.log(request.getAllResponseHeaders());

问题不在于Jquery或Ajax。响应标头由服务器设置。您要发送请求的服务器,不是设置标头!简单!!!!

当我尝试使用我的服务器时[某些响应因安全而模糊] 我得到了以下输出

Snap of Console output

相关问题