views:

182

answers:

2

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&amp;tagmode=any&amp;format=json&amp;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!

+3  A: 

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.

Nick Berardi
Thanks so much, Nick! Guess I wasn't looking in the right place. I appreciate the help.
Bungle
+1  A: 

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&amp;tagmode=any&amp;format=json&amp;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.

Bungle