views:

273

answers:

3

Until the cross-site XHR API becomes widely supported, what is the best way to make a cross-site request through JavaScript? I've been using iFrames, but those can get a bit messy. Is there a better way? (By better, I mean easier to work with.)

Also, I'd prefer to see pure JavaScript code, not a framework such as jQuery, etc. I'm using my own mini-framework and I don't want to have to look up how they did it.

EDIT: I forgot to mention, I have no control over the target server, so I can't use the dynamic <script> tags method.

+3  A: 

There are 2 common ways I know of. One is using a proxy on your server, basically a php file fetching the data for you.

The other is using dynamic script tags. More info here:

http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

Page 9 of this slideshow also has some info:

http://bulletproofajax.com/workshop/slides/04formats.html

動靜能量
I have no control over the target's server, so the second method wouldn't work. But +1 for the proxy method, didn't think about that.
musicfreak
Do not try some hacking thing, use a proxy. If you are afraid of someone using the proxy for no good, lock it down as tight as you can so it can only get what you need it to get.
epascarello
A: 

If the data you are trying to grab is JSON, look into JSONP. It works by injecting a <script> tag into the DOM referencing a script on the remote server. The server on the other end returns some json/javascript style response calling a "callback" function with the data. Basically the remote script will looks something like this:

callbackfunc({'somedata':'testing'});

Where callbackfunc was a function you defined in your script.

gnarf
+1  A: 

You could also take a look at easyxss (http://code.google.com/p/easyxss/wiki/InvokingRemoteMethods) . With only a few lines of code you can get method calls that work across the domain-boundry.

Sean Kinsey
Hmm, looks interesting. +1
musicfreak