views:

188

answers:

6

I need to send a GET request to another domain preferably using jQuery. This isn't a same origin policy bypass because I don't need to get a response. For instance using JavaScript I know I can do this:

document.write('<img src="http://somedomain.com/someapp.php?data='+data+'&gt;')

Is there a better way using jQuery?

A: 

You can attach script tags to the DOM using JS.

var scrElem=document.createElement("script");
scrElem.type="text/javascript"; //maybe not required
scrElem.src="http://bla";
document.getElementsByTagName("head")[0].appendChild(scrElem);

If you want to be really tidy about it, you could also give the script element an id attribute so you can remove it when it's done its job.

Alternatively, jQuery getScript wraps all this up nicely.

spender
`getScript` won't work because it may throw an error the response may not be valid javascript -- even if he doesn't need the response it will still try to parse it.
CD Sanchez
although it sounds like OP is probably in charge at "other domain", so can craft response accordingly.
spender
A: 

Specifically, add it to the <head> element. I'm not sure if it works in IE.

0x90
A: 

You can do like this:

 $('selector').append('<img width="0" height="0" src="http://somedomain.com/someapp.php?data=' + encodeURIComponent(data) + '>');
Bang Dao
+2  A: 

I presume you don't need it in the DOM, so you could do this:

var img = new Image();
img.src = 'http://somedomain.com/someapp.php...' + ...;
Martin
A: 

There's no need to inject the <img> into the DOM.

Simply:

var request=$('<img/>').attr('src','http://somedomain.com/someapp.php?data='+data);

This will create a new img-Element, similar to new Image() . If there is a src-attribute provided, the image will be loaded(the request sended)

But I think it's not a better way, I's another way. It,s the jQuery-way to do Martin's Proposal.

However, it would be good if the requested ressource didn't produce large response, because the response will be loaded anyway.

Dr.Molle
+1  A: 

You can create the <img> element but do nothing with it...it'll cause an immediate fetch, resulting in a GET request:

$('<img src="http://somedomain.com/someapp.php?data='+data+'"&gt;');
Nick Craver
You sir are a ninja of high Fortitude and Wisdom.
Rook