admin管理员组

文章数量:1434960

Is jQuery able to read JSON data from X-JSON HTTP headers returned by the server? I've been searching through the jQuery docs, but all the examples I can find use JSON returned in the request body rather than the headers.

Is jQuery able to read JSON data from X-JSON HTTP headers returned by the server? I've been searching through the jQuery docs, but all the examples I can find use JSON returned in the request body rather than the headers.

Share Improve this question asked Nov 29, 2009 at 2:23 friedofriedo 67.1k17 gold badges118 silver badges186 bronze badges 2
  • 2 Just curious, why would you want to use a header to transport data? – gahooa Commented Nov 29, 2009 at 2:24
  • 2 @gahooa: Prototype encourages it, because it's "easier" than multipart responses: devcentral.f5./weblogs/macvittie/archive/2009/04/07/… and ruby-forum./topic/94728 shed light on the situation. – Jed Smith Commented Nov 29, 2009 at 2:36
Add a ment  | 

2 Answers 2

Reset to default 5

Yes, you need to call the getResponseHeader method of the XMLHttpRequest object, and do the JSON de-serialization manually:

function getHeaderJSON(xhr) {
  var json;
  try { json = xhr.getResponseHeader('X-Json') }
  catch(e) {}

  if (json) {
    var data = eval('(' + json + ')'); // or JSON.parse or whatever you like
    return data
  }
}

Note that the try/catch is for some versions of Firefox where if the header is not present an error is thrown. I can't remember which version(s) were affected.

You have a couple ways to get a reference to the XMLHttpRequest object in jQuery:

  1. hook into the plete callback of the ajax request, as opposed to the expected success callback (jQuery is kind of inconsistent wrt to what args are passed in what order to what callback function or global ajax trigger):

    $.ajax({
      // ...
      plete: function(xhr) {
        var data = getHeaderJSON(xhr);
        // do with data as you wish
      }
    })
    
  2. Alternatively you can save a reference to the XMLHttpRequest object returned to you from calls to .ajax/.get/.post etc, via a Closure. This allows you to use it inside whatever callback you choose (ie success or plete, or error for that matter):

    var xhr = $.ajax({
      // ...
      success: function() {
        var data = getHeaderJSON(xhr); // access xhr var via closure
        // do with data as you wish
      }
    });
    

So to answer your title directly: no, jQUery obviously doesn't support this OOTB.

as of 1.4 jQuery's success: callback receives XMLHttpRequest -- (data,textStatus,XMLHttpRequest). So you don't have to use the plete: callback anymore, as laid out above.

Wish I could reply to the previous answer instead of adding a new answer.

本文标签: javascriptDoes jQuery support reading JSON from XJSON HTTP headersStack Overflow