简体   繁体   English

jQuery和AJAX响应标头

[英]jQuery and AJAX response header

So I've got this jQuery AJAX call, and the response comes from the server in the form of a 302 redirect. 因此,我收到了这个jQuery AJAX调用,响应以302重定向的形式来自服务器。 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. 我想进行此重定向并将其加载到iframe中,但是当我尝试使用JavaScript警报查看标头信息时,即使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移到响应正文,我知道这是最简单的解决方案,因此,解析标头的任何帮助都非常出色。

cballou's solution will work if you are using an old version of jquery. 如果您使用的是旧版的jquery,则cballou的解决方案将起作用。 In newer versions you can also try: 在较新的版本中,您也可以尝试:

  $.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 docs the XMLHttpRequest object is available as of jQuery 1.4. 根据文档 ,XMLHttpRequest对象从jQuery 1.4开始可用。

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对象将仅通过xhr.getResponseHeader('Header')通过xhr.getResponseHeader('Header') )检索标xhr.getResponseHeader('Header')标头是一个简单的响应标头

  • 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-Headers header 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 Location header through the XMLHttpRequest object if, and only if, the header below is also present: 关于所讨论的情况,如果它是一个CORS请求,则仅当并且也存在以下标头时,才能够通过XMLHttpRequest对象检索Location标头:

Access-Control-Expose-Headers: Location

If its not a CORS request, XMLHttpRequest will have no problem retrieving it. 如果它不是CORS请求,则XMLHttpRequest检索它不会有问题。

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

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. 关于AJAX和302重定向的不幸事实是,您无法从返回中获取标头,因为浏览器从未将标头提供给XHR。 When a browser sees a 302 it automatically applies the redirect. 当浏览器看到302时,它将自动应用重定向。 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. 在这种情况下,您会在firebug中看到标头,因为浏览器已获得标头,但在ajax中却看不到标头,因为浏览器未传递标头。 This is why the success and the error handlers never get called. 这就是为什么成功和错误处理程序永远不会被调用的原因。 Only the complete handler is called. 仅调用完整的处理程序。

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. 这是关于此主题的一些stackoverflow帖子。 Some of the posts describe hacks to get around this issue. 一些帖子描述了解决此问题的黑客方法。

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(临时)

The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. jQuery使用的基础XMLHttpRequest对象将始终以静默方式进行重定向,而不是返回302状态代码。 Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. 因此,您不能使用jQuery的AJAX请求功能来获取返回的URL。 Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe: 相反,您需要将所有数据放入表单中,然后将target属性设置为iframe的name属性值的表单提交:

$('#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.do page 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将被重定向到最终目标。

try this: 尝试这个:

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

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'));
        });
    }

+1 to PleaseStand and here is my other hack: +1到PleaseStand,这是我的另一个技巧:

after searching and found that the "cross ajax request" could not get response headers from XHR object, I gave up. 搜索后发现“跨Ajax请求”无法从XHR对象获取响应头,我放弃了。 and use iframe instead. 并改用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()  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM