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.
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:
hook into the
completecallback of the ajax request, as opposed to the expectedsuccesscallback (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 } })Alternatively you can save a reference to the
XMLHttpRequestobject returned to you from calls to.ajax/.get/.postetc, via a Closure. This allows you to use it inside whatever callback you choose (iesuccessorcomplete, orerrorfor 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 complete: callback anymore, as laid out above.
Wish I could reply to the previous answer instead of adding a new answer.