Same-domain Requirements and XmlHttpRequest
On the JSON v XML debate: what good is a same-domain requirement for XmlHttpRequest if you can do a GET on any host via a SCRIPT element? It’s like saying “applets can’t contact arbitrary hosts through sockets but URLConnections are ok”.
+1.
Update: My insightful commenters seem to suggest I don’t know what I’m talking about, and it seems they’re right — I guess I have some more reading to do …
Seems that way doesn’t it, but in practice script tags and XHR requests have a fundamental difference. Script tags (to my knowledge) must be written/executed as the page loads. XHR requests can happen anytime after the page loads. In many newer Ajax application, the page loads once and never again - more like a web-based fat client. The advantages of doing this is that you can maintain a lot of state on the client side (DOM state goes away between page loads) and of course you don’t get the jarring full-screen refresh behavior.
So in a lot of modern Ajax apps, your ability to dynamically load new code or data on the fly is generally constrained to XHR which makes the cross-domain restriction a big deal (but ultimately a good idea).
Note that some newer Ajax toolkits like Dojo provide other IO mechanisms (e.g. IFrame IO) that do allow cross-URL IO post-page load - not as clean as XHR, but you can definitely do it.
PS - I wrote an article for developerWorks on some of the architectural advantages of the stateful Ajax client architecture. It’s at the URL below: http://www-128.ibm.com/developerworks/java/library/wa-ajaxarch/
PPS - I’ll post this same comment to the original guy (Matthias’s) blog.
FYI, here’s a page on Dojo’s “Cross Domain XMLHttpRequest using an IFrame Proxy” mechanism:
http://manual.dojotoolkit.org/WikiHome/DojoDotBook/Book75
-1, misleading.
Just doing a GET on any host isn’t very interesting. You can do that with an img tag.
Without the same-domain restriction for XmlHttpRequest we would face a wave of (literally) unstoppable CSRF attacks, but the script src hack doesn’t suffer from the same vulnerability: you can do the GET, but the local script can’t read the response. The browser can execute it, but that’s all. It chokes on anything but JavaScript, so it can’t be used to load arbitrary pages. GET them, yes, but not read them.
That’s why the Yahoo APIs wrap JSON in a user-defined function call. The function is called when the remote script is loaded. The local script never gets access to the raw response the way it would with XmlHttpRequest.