我可以用一个静态的(即predetermined)回调函数名,要求JSONP使用jQuery的时候?可以用、回调、静态、函数

2023-09-11 00:55:41 作者:人心太涼、別太善良

借助 jQuery的文档列出了使用$ .getJSON要求JSONP下面的例子:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",   功能(数据){     $每个(data.items,功能(I,项目){       $(< IMG />中)。ATTR(src用户,item.media.m).appendTo(#图像);       如果(我== 3)返回false;     });   });

,而不是使用这种方法,其产生是因为该参数的动态回调函数名:

  jsoncallback =?
 

我希望能够设置提前硬codeD功能的名称,如:

  jsoncallback =测试
 
10张图让你彻底理解回调函数

这工作,在我运行该脚本和JSONP,我回来了包裹在调用JSON对象来测试(感)。

不过,我想不出如何设置回调函数。难道不应该是这么简单?

 功能测试(数据){
  的console.log(数据);
}

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=test");
 

当我尝试了,我回来了JSONP被包裹在试验(+),但功能测试(),我已经确定不会被调用。我失去了一些东西?

感谢您的帮助!

解决方案

随着的定义文档你用下面的方法

  jQuery.getJSON(...)
 

您需要指定回调=?制作JSONP呼叫时。我通常只使用此为JSON的响应类型。对于JSONP的响应类型,您要使用:

  jQuery.get(...)
 

和指定的键入为JSONP。见关于这个问题这文档。但是,这也势必有有一个回调的事实=?

我觉得你要找的是这个:

  jQuery.getScript(...)
 

这应该执行什么方法,你在你的回调定义

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=?

I want to be able to set that in advance to a hardcoded function name, like this:

jsoncallback=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");

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?

Thanks for any help!

解决方案

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.

 
精彩推荐