views:

115

answers:

2

It looks like I can't make a call outside the current domain name with "AJAX". But I'm able to call the twitter API (with JSON) in JQuery... aren't both using the XMLHTTP Object? If so (or not), why am I able to call another domain name with JSON (using JQuery) but not with AJAX ? What's the difference between Ajax and JSON anyway?

+7  A: 

The twitter API uses JSONP, which doesn't use XMLHTTPRequest, but uses a <script> tag to include "foreign" javascript. This script then calls a function within your own javascript.

Google Maps integration in third-party websites wouldn't be possible without this "hack" (that's actually what it is: a hack).

Here's more info on JSONP:

http://ajaxian.com/archives/jsonp-json-with-padding

or in the wikipedia article on JSON:

http://en.wikipedia.org/wiki/JSON#JSONP

Philippe Leybaert
Aaah.. that make sense! thanks!
A: 

JSON is a file format, whereas AJAX is a technique in JavaScript for sending and receiving data from the web server after the page has finished loading. The X in AJAX is for XML (also a file format) that's an alternative to JSON, but it's a bit of a misnomer because quite a lot of things that people call AJAX don't actually use XML at all.

Mr LeyBaert's link on JSONP is very helpful in terms of practically explaining what's going on in the Twitter API; it's not XMLHTMLRequesting at all, there's just another script tag that points at a javascript file on the twitter website, that then gets loaded along with the rest of your page, when the page is first loaded.

You can get neat things through this, but I don't think you can do it after the page has loaded (as with AJAX) unless you start messing about with hidden IFrames or similar. If you really need to get AJAX style things without XMLHTTPRequests that's what you want to look into; dynamically adding an IFrame to the document that references a page that requests a script (or similar) from another site. There's some discussion of the pros and cons of this here.

PimTerry
It's perfectly fine to do it after a page has loaded. If you're using jQuery, it's very easy to do, and works in all browsers. In fact, Google Maps does all it's server communication through JSONP, and it's all done after the page has loaded.
Philippe Leybaert
PimTerry, it is perfectly possible to insert a `<script>` tag into the document dynamically. Assuming you know and trust the server you're calling, The only real problem is knowing when the script is actually loaded, and this is typically solved with a callback function. The problem in that is that the service needs to support that, so you can't control all from the client side, the server has to use a predefined callback, or be able to accept one via the request.
Roland Bouman