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.
Flickr Gallery
Recent Comments
Kevin says,
use forward slashes rather than back slashes. You would format ...
yiannos says,
very helpfull hint...you saved me a lots of money......
Tony Garcia says,
Hey Kevin,
Just curious -- are you running CF9 in ...
Sami says,
Okay, im somewhat new to macs and I don't know ...
Aaron says,
I got to meet this guy too. Seemed too laid ...