jQuery 和 AJAX 响应标头

发布于 2024-08-07 18:16:05 字数 404 浏览 7 评论 0原文

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

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

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

我真的无法访问服务器端的东西,以便将 URL 移动到响应正文,我知道这将是最简单的解决方案,因此解析的任何帮助标题会很棒。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

我爱人 2024-08-14 18:16:05

如果您使用旧版本的 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'));
   }
  });

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

cballou's solution will work if you are using an old version of jquery. 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.

野生奥特曼 2024-08-14 18:16:05

如果这是 CORS 请求,您可能会在调试工具(例如 Chrome- >Inspect Element->Network),但如果此类标头是 简单响应标头:

  • Content-Type
  • Last-modified
  • < code>Content-Language
  • Cache-Control
  • Expires
  • Pragma

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

对于上述情况,如果是 CORS 请求,则只能通过 XMLHttpRequestLocation 标头> object 当且仅当下面的标头也存在时:

Access-Control-Expose-Headers: Location

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

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:

  • 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.

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:

Access-Control-Expose-Headers: Location

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

挽清梦 2024-08-14 18:16:05
 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });
 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });
无言温柔 2024-08-14 18:16:05

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

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

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

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

在 JavaScript 中捕获 302 FOUND

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

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.

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.

How to manage a redirect request after a jQuery Ajax call

Catching 302 FOUND in JavaScript

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

淡紫姑娘! 2024-08-14 18:16:05

jQuery 使用的底层 XMLHttpRequest 对象将始终默默地遵循重定向,而不是返回 302 状态代码。因此,您无法使用 jQuery 的 AJAX 请求功能来获取返回的 URL。相反,您需要将所有数据放入表单中,并使用 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();

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

The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather 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 target attribute set to the value of the name attribute of the iframe:

$('#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.

囚我心虐我身 2024-08-14 18:16:05

更新 2018 JQUERY 3 及更高版本

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

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

UPDATE 2018 FOR JQUERY 3 AND LATER

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'));
        });
    }
策马西风 2024-08-14 18:16:05

试试这个:

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

try this:

type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
    var headers = XMLHttpRequest.getAllResponseHeaders();
}
望笑 2024-08-14 18:16:05

+1 表示请起立
这是我的另一个黑客:

在搜索后发现“跨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()  

+1 to PleaseStand
and here is my other 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.

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()  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文