CROSS-DOMAIN AJAXWITH JSONPThe unofficially official kludge that defeatssame-origin policy
For security, we cant have any oldweb page changing data from any oldweb service• The same-origin policy is built into browsers to prevent that.
"Same-origin" means same protocol, domain, and port• From the W3C• Say you have a page at http://www.tic.com and try to run a service on … URL Outcome Reasonhttp://www.tic.com/dir2/other Successhttp://www.tic.com/dir/inner/another Successhttps://www.tic.com/secure Failure Different protocolhttp://www.tic.com:81/dir/etc Failure Different porthttp://service.tic.com/dir/other Failure Different host
You cant run scripts but you candownload resources from a foreign webserver So heres the trick … download a "script" from the site hosting the web service that "happens" to have data in it Extract the returned data – voila!
We can process JSONP responses with$.getJSON()• JSON with Padding• If the server is set up to respond with JSONP, youre good to go• The $.getJSON() request gets the script and unwraps it, leaving the raw JSON data.• Sound kludgey to you?
Conclusion• Browsers are written to forbid cross-domain scripting• To bypass that, servers can write their scripts to handle JSONP requests• We can make JSONP requests on the client-side with $.getJSON()
Lab• Flickr tutorial – pp. 383 – 387• Google maps tutorial – pp. 397 - 400