In my application I have a website on one sub-domain (dev.u413.com) and I use jQuery to make an ajax request to a JSON api on another sub-domain (api.u413.com). When I inspect the requests in Chrome dev tools and Firefox Firebug it appears my requests are being prevented by the Access-Control-Allowed-Origin
. I set document.domain
to a suffix of the current domain: document.domain = 'u413.com';
.
Here is my request:
$.ajax({
dataType: 'json',
data: { parseAsHtml: true, cli: 'help' },
url: 'http://api.u413.com/',
success: function (response) {
alert(response.Command);
}
});
If I modify the ajax request to be on the same domain then the request is successful.
$.ajax({
dataType: 'json',
crossDomain: false,
data: { parseAsHtml: true, cli: 'help' },
url: 'http://dev.u413.com/',
success: function (response) {
alert(response.Command);
}
});
Why does this happen? The browser shouldn't complain about cross-domain problems since I set document.domain
to a common suffix of both sub-domains as per the guidelines on the same origin policy.
I have the app working with jsonp currently but I feel like proper ajax requests should be working as per the same origin policy I linked above. I'd rather not use jsonp if I don't have to. Is it not possible to make regular ajax requests across sub-domains?
document.domain
doesn't work with AJAX. It is intended for cross domain iframe and window communication. In your case you are violating the same origin policy (last line of the table) so you need to use either JSONP or server side bridge.
Here's a very nice guide which illustrates different techniques for achieving cross domain AJAX requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With