Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

ajax - JQuery's getJSON() not setting Accept header correctly?

It looks like people have had issues with Accept headers in the past, but I'm not sure my issue is related. Using jQuery 1.4.2, I'm having trouble getting JSON with getJSON(). I can watch the request / response in Firebug and it looks like the source of the problem is that the resource in question returns different results depending on the Accept header. Even though the docs say it should be set, in Firebug it shows up as "/" -- obviously, I want "application/json". Is this a known bug? Am I supposed to be setting some flag I'm not aware of?

ETA: The request is cross-site, if that matters, but I'm passing a callback=? query parameter so JQuery is (successfully!) treating it as JSONP. The service I'm calling in this particular case supports an accept override query parameter (&accept=application/json), so I got it to work manually, but I still consider the header screwup to be strange and was hoping I'd be able to fix it, so I don't run into this again when dealing with a different service that might not be so forgiving. I don't have an easy way to copy/paste the code from my development environment but here's the gist:

$.getJSON(baseURL + "?item=" + itemNum + "&callback=?", function(data){
  console.log(data);
}

As you can see, this is not exactly complex, and should (I'm 99% sure...) result in an XHR being sent with an Accept header of application/json. Like I said, that's not happening, per Firebug's Net console. If it matters, this is in Firefox 3.6.8.

ETA Again: For anybody still reading this, yes, it's still happening, and no, I have no idea why. Like I said, simple getJSON() call, really basic syntax, cross site, treated as JSONP because it includes a callback query parameter. Still open to suggestions!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not a bug.

Since your call is cross-domain, your browser will not allow you to make XHR calls (same-origin policy). Internally, jQuery is working around this using the "<script> tag hack", to make the cross-domain call (this is the fundemental idea behind the JSONP data type). Since the call is made using the tag, it is simply not possible for jQuery to modify the accepts portion of the header.

jQuery works its magic by hiding these details from you, but unfortunately in this case you seem to be subject to the Law of Leaky Abstractions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...