0 Comments

Working with jQuery and jsonp

By Kevin / Posted on 03 November 2011

I was recently working on a project for a client and needed to use Jquery’s getJson() function with Jsonp.  I had tried this in the past but kept getting ‘parseerror’ responses and could not really figure out what was going on.  I had pasted my json code into the json validator and it said that it was valid.  The documentation on Jquery’s website was pretty sparse.   It took me a while to figure this one out and, as usual, the solution was so simple.

When you are using getJson() or ajax() all that you need to do is add the following:

callback=?

to the url and jQuery will automatically add a callback variable to the url in place of the ‘?’.  Then you need to use that function in your json declaration file to create the jsonp format.

For example, if you have a json file like:

[{"value":"1","label":"One"},{"value":"2","label":"Two"}]

You would want to create a function using the callback variable that was passed in the url.  In Coldfusion it would look like:

#callback#([{"value":"1","label":"One"},{"value":"2","label":"Two"}]);

jQuery will then read in the response and parse it as normal json.  Now you can access your json files across domains.

Easy huh?  Hopefully this helps someone.

 

Categories

Coldfusion, JavaScript, jQuery

 
 
 

Do you have something to say?