3

I'm serving my JSONP JavaScript file on a static file server - GitHub Pages.

This means I can't dynamically set the JSONP callback function name on the server...

Dynamic example - PHP

header('Content-Type: text/javascript; charset=utf8');
$data = '{ "foo":"bar" }'; // json string
echo $_GET['callback'] .'('.$data.');'; // function name set via ?callback=xyz

jQuery.ajax() has a jsonpCallback param to define a static callback function name. So I can server a javascript file e.g. test-jsonp.js with the following content:

Static example - JavaScript file

jsonpCallbackABC({ "foo":"bar" });

However the jQuery documentation suggests static is less desirable.

http://api.jquery.com/jQuery.ajax/

jsonpCallback
Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

Can someone please go into more detail on the pitfalls of static JSONP function names?

Community
  • 1
  • 1
Chris Jacob
  • 11,878
  • 7
  • 47
  • 42

2 Answers2

3

It's simple: Does your page do simultaneous requests using jsonp (mostly pages do as the requests are asynchronously started from page events) ?

If so, the responses will be harder to separate and process if you have a single point of entry (single jsonp callback).

I used a static callback function name on a recent project, but it was used in synchronous mode, and only once over the page lifetime, so it wasn't a problem to make the callback name static.

Monoman
  • 721
  • 10
  • 12
  • I wonder if $.getScript() might be a "better" option when dealing with a static function name ... Thinking of returning a namespaced var, as opposed to trying to call a function http://api.jquery.com/jQuery.getScript What do you think? – Chris Jacob May 17 '11 at 17:46
  • +1 My goodness, I was debugging for a while before I stumbled across this. It appears so obvious now! If you have multiple jsonp ajax requests on a single page, you need multiple callback functions, not one callback function shared by all your ajax requests. This was especially problematic because one of my requests was cached and the other one wasn't. @Monoman, Thank you for the helpful response! – Landon Poch Feb 12 '14 at 00:15
1

If there's an other place in your code where a function with the same name is defined, it will collide with the function in the jsonp.

You could also have problems if you try to call the same service in different parts of the page, all the ajax call will receive the same reponse, it could cause difficult to debug behaviors.

Guillaume Davion
  • 434
  • 4
  • 12