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…
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?
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.