> > For example:
> >
> > JSON: { "test":"value" }
> > JSONP: myCallback({ "test":"value" })
> >
> > As you can see, the JSON part is the same, but putting it inside a 
> > function call makes the whole thing executable code that will run 
> > automatically when the script is loaded - assuming of 
> > course that you have defined a "myCallback" function.

> I havn't gotten the "ah ha" yet here with JSONP. :-)
> 
> What is executed?  Is JSON syntax considered "code?"  A 
> little flow description might help.
> hmmmmm,  I think I got it.   I can populate a web page with JSON data
> and process it when the page loads or  get it from AJAX, and 
> with the callback, pass and process the JSON data?

JSON syntax is indeed executable JavaScript code - almost. It is a subset of
the JavaScript object literal notation.

Take the JSON example above and try to execute it:

{ "test":"value" }

 Paste it into the Firebug command line - that's a great way to test code
snippets.

You will get a syntax error. It's valid JavaScript code, but not quite a
complete statement. Now try this:

var test = { "test":"value" };

That will work without any errors.

Now try this:

function myCallback( json ) { alert( json.test ); }

myCallback({ "test":"value" });  // JSONP

It should open an alert box with "value" in it. Straightforward stuff,
right?

That test() function call is JSONP, and it's a complete executable statement
that will *run some code*.

Why is that important?

Suppose you want to support cross-domain downloads of your REST API directly
from JavaScript without using a proxy server on the customer's website. The
best way to do that is with a dynamic script tag. But to use the data, you
need to have the script *run some code*. The way to do that is with a
function call as in that last example.

That's all JSONP is: JSON data wrapped inside a function call. You define
the function before loading the dynamic script tag. When the script loads,
it calls that function and passes it the JSON data as an argument.

This is why I've been asking whether you want to allow your customers to
access your REST API directly, cross-domain from JavaScript code. If you do,
then you need to use dynamic script tags and JSONP. If you require your
customer to set up a forwarding proxy on their own server, then they can use
AJAX.

Of course, from an API point of view, it's simple: Provide both options.
Once you support JSON, it's very little extra work - only a few lines of
code - to support JSONP as well.

> I do have to double check some work.  jQuery seems to have a 
> problem with evaluating scripts in HTML results, something 
> the other library, like prototype.js does not.

See my reply to your other message about that...

-Mike

Reply via email to