jQuery 和 AJAX 响应头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1557602/
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 11:42:48  来源:igfitidea点击:

jQuery and AJAX response header

jqueryajaxredirectheaderhttp-status-code-302

提问by Shane

So I've got this jQuery AJAX call, and the response comes from the server in the form of a 302 redirect. I'd like to take this redirect and load it in an iframe, but when I try to view the header info with a javascript alert, it comes up null, even though firebug sees it correctly.

所以我得到了这个 jQuery AJAX 调用,响应以 302 重定向的形式来自服务器。我想使用此重定向并将其加载到 iframe 中,但是当我尝试使用 javascript 警报查看标头信息时,它显示为 null,即使 firebug 正确看到它。

Here's the code, if it'll help:

这是代码,如果有帮助的话:

$j.ajax({
    type: 'POST',
    url:'url.do',
    data: formData,
    complete: function(resp){
        alert(resp.getAllResponseHeaders());
    }
});

I don't really have access to the server-side stuff in order to move the URL to the response body, which I know would be the easiest solution, so any help with the parsing of the header would be fantastic.

为了将 URL 移动到响应正文,我真的无权访问服务器端的内容,我知道这将是最简单的解决方案,因此解析标头的任何帮助都会很棒。

回答by rovsen

cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:

如果您使用的是旧版本的 jquery,cballou 的解决方案将起作用。在较新的版本中,您还可以尝试:

  $.ajax({
   type: 'POST',
   url:'url.do',
   data: formData,
   success: function(data, textStatus, request){
        alert(request.getResponseHeader('some_header'));
   },
   error: function (request, textStatus, errorThrown) {
        alert(request.getResponseHeader('some_header'));
   }
  });

According to docsthe XMLHttpRequest object is available as of jQuery 1.4.

根据文档,XMLHttpRequest 对象从 jQuery 1.4 开始可用。

回答by acdcjunior

If this is a CORS request, you may see all headers in debug tools (such as Chrome->Inspect Element->Network), but the xHR object will only retrieve the header (via xhr.getResponseHeader('Header')) if such a header is a simple response header:

如果这是CORS 请求,您可能会在调试工具(例如 Chrome->Inspect Element->Network)中看到所有标头,但xhr.getResponseHeader('Header')如果此类标头是简单的响应标头,则 xHR 对象将仅检索标头(via ):

  • Content-Type
  • Last-modified
  • Content-Language
  • Cache-Control
  • Expires
  • Pragma
  • Content-Type
  • Last-modified
  • Content-Language
  • Cache-Control
  • Expires
  • Pragma

If it is not in this set, it must be present in the Access-Control-Expose-Headersheader returned by the server.

如果它不在此集中,则它必须存在于服务器返回的Access-Control-Expose-Headers标头中。

About the case in question, if it is a CORS request, one will only be able to retrieve the Locationheader through the XMLHttpRequestobject if, and only if, the header below is also present:

关于所讨论的案例,如果是 CORS 请求,则只有当且仅当以下标头也存在时,才能Location通过XMLHttpRequest对象检索标头:

Access-Control-Expose-Headers: Location

If its not a CORS request, XMLHttpRequestwill have no problem retrieving it.

如果它不是 CORS 请求,XMLHttpRequest则检索它没有问题。

回答by keithics

 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });

回答by DRaehal

The unfortunate truth about AJAX and the 302 redirect is that you can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.

关于 AJAX 和 302 重定向的不幸事实是,您无法从返回中获取标头,因为浏览器从未将它们提供给 XHR。当浏览器看到 302 时,它会自动应用重定向。在这种情况下,你会在 firebug 中看到 header,因为浏览器得到了它,但你不会在 ajax 中看到它,因为浏览器没有通过它。这就是成功和错误处理程序永远不会被调用的原因。只调用完整的处理程序。

http://www.checkupdown.com/status/E302.html

http://www.checkupdown.com/status/E302.html

The 302 response from the Web server should always include an alternative URL to which redirection should occur. If it does, a Web browser will immediately retry the alternative URL. So you never actually see a 302 error in a Web browser

Here are some stackoverflow posts on the subject. Some of the posts describe hacks to get around this issue.

这里有一些关于这个主题的 stackoverflow 帖子。一些帖子描述了解决这个问题的技巧。

How to manage a redirect request after a jQuery Ajax call

如何在 jQuery Ajax 调用后管理重定向请求

Catching 302 FOUND in JavaScript

在 JavaScript 中捕获 302 FOUND

HTTP redirect: 301 (permanent) vs. 302 (temporary)

HTTP 重定向:301(永久)与 302(临时)

回答by PleaseStand

The underlying XMLHttpRequest object used by jQuery will always silently follow redirectsrather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the targetattributeset to the value of the nameattribute of the iframe:

jQuery 使用的底层 XMLHttpRequest 对象将始终默默地遵循重定向而不是返回 302 状态代码。因此,您不能使用 jQuery 的 AJAX 请求功能来获取返回的 URL。相反,您需要将所有数据放入一个表单中,并提交表单,并将target属性设置为nameiframe的属性值:

$('#myIframe').attr('name', 'myIframe');

var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);

form.appendTo(document.body);
form.submit();

The server's url.dopage will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.

服务器的url.do页面会被加载到 iframe 中,但是当它的 302 状态到达时,iframe 将被重定向到最终目的地。

回答by Corey Ballou

try this:

尝试这个:

type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
    var headers = XMLHttpRequest.getAllResponseHeaders();
}

回答by sticky_elbows

UPDATE 2018 FOR JQUERY 3 AND LATER

JQUERY 3 及更高版本的 2018 年更新

I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:

我知道这是一个老问题,但上述解决方案都不适合我。这是有效的解决方案:

//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
        var jqxhr = $.ajax({
            type: requestType,
            url: urlTo
        });
        //this section is executed when the server responds with no error 
        jqxhr.done(function(){

        });
        //this section is executed when the server responds with error
        jqxhr.fail(function(){

        })
        //this section is always executed
        jqxhr.always(function(){
            console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
        });
    }

回答by u445908

+1 to PleaseStand and here is my other hack:

+1 给 PleaseStand,这是我的另一个 hack:

after searching and found that the "cross ajax request" could not get response headers from XHR object, I gave up. and use iframe instead.

搜索后发现“跨ajax请求”无法从XHR对象获取响应头,就放弃了。并改用 iframe。

1. <iframe style="display:none"></iframe>
2. $("iframe").attr("src", "http://the_url_you_want_to_access")
//this is my aim!!!
3. $("iframe").contents().find('#someID').html()