12 jsonp

1,094 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,094
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

12 jsonp

  1. 1. CROSS-DOMAIN AJAXWITH JSONPThe unofficially official kludge that defeatssame-origin policy
  2. 2. Pop quiz …•  How do you get jQuery into your project?•  Other JavaScript/jQuery libraries?•  Is this legal?<img src="http://otherSite.com/images/usher.jpg" />!
  3. 3. The same origin policy keeps JavaScriptfrom becoming an XSS monster
  4. 4. 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.
  5. 5. "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
  6. 6. But some So how do theyweb servers provide the data when the browsersWANT to wont allow it?provide JSONdata to othersites andJavaScript.
  7. 7. 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!
  8. 8. 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?
  9. 9. What is the padding?•  Can be anything as long as it looks like an executable JavaScript call. •  Wrap the response in a function call •  Set a variable •  Whatever you want it to be, really. :-)•  The JSONP standard proposed isfunctionName({JSONDataGoesHere});!
  10. 10. Lets do this with Flickr
  11. 11. 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()
  12. 12. Lab•  Flickr tutorial – pp. 383 – 387•  Google maps tutorial – pp. 397 - 400

×