Can I use a static (i.e., predetermined) callback function name when requesting JSONP with jQuery?

為{幸葍}努か 提交于 2019-12-04 14:31:54

As defined in the documentation for you to use the following method

jQuery.getJSON(...)

you need to specify callback=? when making a JSONP call. I usually only uses this for response types of "json". For response types of "jsonp", you want to use:

jQuery.get(...)

and specify the type as "jsonp". See this documentation on the subject. But that is also bound by the fact of having to have a callback=?.

What I think you are looking for is this:

jQuery.getScript(...)

Which should execute whatever method you have defined in your callback.

Bungle

Ah, the "Related" sidebar section saved me here. After I submitted this question, I found a similar one already asked:

using a named function as the callback for $.getJSON in jQuery to satisfy Facebook request signing demands

Duncan's answer from Oct. 15 solved this for me:

window.fixed_callback = function(data){
  alert(data.title);
};

$(function() {
  $.getScript("http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&tagmode=any&format=json&jsoncallback=fixed_callback", function(data) {
  alert('done'); } );
});

I guess the key is using $.getScript instead of $.getJSON. One can still specify an anonymous callback function in the parameters of the $.getScript method, which will be executed after the callback function named in the request URL parameters ("fixed_callback" in this case). Hope this helps someone down the road.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!