L
Lawrence Krubner
Almost invariably, they use the so called "script tag hack". There's
currently no better way to do it. The idea is:
1.- Create and insert in your page an empty <script> tag whose .src
contains the parameters:
e.g. script.src= "example.com/mapsData.json?
lat=0.0&long=0.0&q=cityName"
2.- The server extracts the paramenters, processes the request and
formats the answer as a json text :
e.g. {'cityName': 'Some City'}
3.- Note that the client is expecting a <script>. A script gets
executed inmediatly after arriving, and it does so at the global
context. So, for example, assigning the json text to a global variable
would do, and this would be a valid <script> to send back:
mapsResponse= {'cityName': 'Some City'};
4.- At the client-side, the data becomes accessible as the global var
mapsResponse.
This is the idea. Data travels encapsulated in scripts, because the
scripts are not subject to the same origin policy. The example above
makes (I hope) it easy to grasp the whole process, although, the truth
is that passing the returned data to a global var as above is not the
most convenient way to do it. Using a callback function is much
better:
1.- Create and insert in your page a <script> tag whose .src contains
the parameters:
e.g. script.src= "example.com/mapsData.json?
lat=0.0&long=0.0&q=cityName&callBack=callBackFuncitonName"
Note the last parameter "callBack=callBackFuncitonName". It tells the
server that we want to have the returned data passed to the function
"callBackFuncitonName".
2.- The server extracts the parameters, processes the request and
respond with a script like this :
callBackFuncitonName({'cityName': 'Some City'});
3.- At the client side, when the script finally arrives it gets
automatically executed (in the global context), IOW, the function
callBackFuncitonName() gets called and receives the data as a
parameter.
Obviously, the callback must be accesible from the global context.
Most of the times you'll find yourself attaching the callBack to your
apps' global object: myApp.mapsThings.callBack() or something like
that. Just pass the "fully qualified name" to the server:
"&callback=myApp.mapsThings.callBack".
Thanks much for all the excellent advice. I wrote it up on my blog and
linked back to your example:
http://www.teamlalala.com/blog/2009...-from-one-domain-to-another-using-javascript/