views:

603

answers:

2

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.

+3  A: 

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 complete 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({
      // ...
      complete: 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 complete, 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.

Crescent Fresh
I didn't know what OOTB means. I looked up: "Out of the box". A variant is "Out of the blue".
nalply
+1  A: 

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

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

Whatcould