在使用jQuery请求JSONP时,我可以使用静态(即预定)回调函数名称吗? [英] Can I use a static (i.e., predetermined) callback function name when requesting JSONP with jQuery?
问题描述
jQuery文档列出了使用$ .getJSON请求JSONP的以下示例:
The jQuery documentation lists the following example of using $.getJSON to request JSONP:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 3) return false;
});
});
而不是使用此方法,由于此参数,将生成动态回调函数名称:
Rather than use this method, which generates a dynamic callback function name because of this parameter:
jsoncallback=?
我想能够提前设置一个硬编码的函数名, p>
I want to be able to set that in advance to a hardcoded function name, like this:
jsoncallback=test
$ b b
这样做,在我运行脚本和JSONP,我回来的JSON对象包裹在调用test()的意义上。
This works, in the sense that I run the script and the JSONP that I get back has the JSON object wrapped in a call to test().
但是,我不知道如何设置回调函数。
However, I can't figure out how to set up the callback function. Shouldn't it be as simple as this?
function test(data) {
console.log(data);
}
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=test");
当我尝试时,我得到的JSONP包裹在test(),但函数我定义的test()从未被调用。
When I try that, I get back the JSONP which is wrapped in test(), but the function test() that I've defined is never called. Am I missing something?
感谢您的帮助!
推荐答案
如要在文档中定义,以使用以下方法
jQuery.getJSON(...)
您需要在进行JSONP调用时指定 callback =?
。我通常只使用这个为json的响应类型。对于jsonp的响应类型,您要使用:
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(...)
并指定 type
为jsonp。请参阅此相关文档。但这也受到必须有 callback =?
的事实的约束。
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=?
.
我认为您是寻找是:
jQuery.getScript(...)
这应该执行您在回调
中定义的任何方法。
Which should execute whatever method you have defined in your callback
.
这篇关于在使用jQuery请求JSONP时,我可以使用静态(即预定)回调函数名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!