jQuery 如何在 AJAX 中获取响应头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34429628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:59:49  来源:igfitidea点击:

How to get Response headers in AJAX

jqueryajax

提问by Anoop LL

I am using the following code for an AJAX call

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

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

        },
        error: function (jqXHR, status) {

        }
    });

This is printing only content-type. In the developer console i can see number of headers in the response. How can i get those headers in AJAX

这仅打印内容类型。在开发人员控制台中,我可以看到响应中的标头数量。我如何在 AJAX 中获取这些标头

enter image description here

在此处输入图片说明

回答by gaowhen

It's seems no problem. I tried and got it works.

好像没问题 我试过并得到了它的工作。

Use JSONPlaceholderand here is my code

使用JSONPlaceholder,这是我的代码

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

the result is

结果是

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

回答by user1071182

On your server you need to add

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

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

and then you will be able to access it in the browser.

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

回答by Mr.Arjun

I used the samecode you used

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

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

Problem is not with Jquery or Ajax. Response headers are set by Server. The server you are sending the request to, is not setting the headers! Simple!!!!

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

When i tried with my server [Some responses blurred for security] i got the following output

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

Snap of Console output

控制台输出的快照