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
2 Answers
Reset to default 5Yes, 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
plete
callback of the ajax request, as opposed to the expectedsuccess
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 } })
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 (iesuccess
orplete
, orerror
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
版权声明:本文标题:javascript - Does jQuery support reading JSON from X-JSON HTTP headers? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745634683a2667483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论