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+'>')
Is there a better way using jQuery?
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+'">');
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...' + ...;
Specifically, add it to the <head> element. I'm not sure if it works in IE.
You can do like this:
$('selector').append('<img width="0" height="0" src="http://somedomain.com/someapp.php?data=' + encodeURIComponent(data) + '>');
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.
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.
精彩评论