I need to do a very simple cross domain api call, and for reasons of overhead/compatibility, dont want to use a fully-featured framework (such a jQuery), since this simple ajax request is pretty much all I need to do. I need to call do a GET
request on http://bar.com
from a page on http://foo.com
. I cannot access the HTTP headers on foo.com
however. I do not need to return data to the browser.
Currently doing the center code hereall results in (on Chrome):
XMLHttpRequest cannot load http://bar.com/api?=x.
Origin http://foo.com is not allowed by Access-Control-Allow-Origin.
http://bar.com/api?=x Failed to load resource
Incidentally, even though this call throws an error, it comes through fine on bar.com
, so another option is basically just catching t开发者_C百科hat error and ignoring it(?). Somewhat unfamiliar with JS though, so not sure if this will fail on other browsers?
Came across this: http://code.google.com/p/xmlhttprequest/source/browse/trunk/source/XMLHttpRequest.js - not sure if this is completely overkill for my use (overhead is pretty critical)?
Yes, this will always fail unless you have set the Access-Control-Allow-Origin
HTTP header to define specific domains which are allowed to be accessed via XHR.
One way you could work around this issue is by using script injection:
function load_script(loc) {
var s = document.createElement('script');
s.src = loc;
document.getElementsByTagName('head')[0].appendChild(s);
}
load_script('http://bar.com/api?=x');
精彩评论