Understanding JSON-P ++++++++++++++++++++ :Posted: 2009-11-26 13:43 :Tags: JavaScript A lot of the time, very simple concepts can be obsucred by the simplifications frameworks make. In this article I want to explain how JSON-P works. Usually when making an API call using JSON you can just use the browser's `XHR `_ object but the browser's security model (the `same origin policy `_) means that you can only get JSON from the same orign that the page was served from. For mashups where you are pulling JSON from different origins this doesn't work. Luckily there's a hack. The browser doesn't restrict where `` Traditional JSON APIs just return JSON data. Let's imagine a http//example.com/api/json returns JSON for a list of blog posts. This means that after the browser has loaded the script you will have the equivalent of this: :: This is great, it works no matter where the JSON is served from, but wouldn't it be better if an event could be triggered when the data was loaded? To do that, rather than returning the JSON data, the server could return the JavaScript source for a function call which passed the JSON data in as an argument so that the generated source looks like this: :: Now when the code is loaded, the ``callback()`` function will be executed. At the moment there isn't a function called ``callback()`` so when using JSON-P you need to define one first. Here's an example: :: Notice that the JSON-P script tag is after the code that defines the callback. You wouldn't want the callback to be called before it has been defined. This time the output from http//example.com/api/json?callback=count_posts might look like this with a different callback name: :: count_posts({ 'posts': [ 'http://example.com/post/345', 'http://example.com/post/2342', 'http://example.com/post/5', ] }) Most JavaScript frameworks support JSON-P. They do so by dynamically generating the ``