Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - Cross-subdomain ajax request denied even when document.domain is set correctly

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...