Cross-site AJAX requests

Enrico Campidoglio picture Enrico Campidoglio · Dec 2, 2008 · Viewed 30.2k times · Source

I need to make an AJAX request from a website to a REST web service hosted in another domain.

Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.

The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.

Here is the JavaScript code that makes the asynchronous call:

var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);

How can I have this work in other browsers beside Internet Explorer?

Answer

redsquare picture redsquare · Dec 2, 2008

maybe JSONP can help.

NB youll have to change your messages to use json instead of xml

Edit

Major sites such as flickr and twitter support jsonp with callbacks etc