跨子域名ajax请求被拒绝,即使document.domain设置正确 [英] Cross-subdomain ajax request denied even when document.domain is set correctly

查看:196
本文介绍了跨子域名ajax请求被拒绝,即使document.domain设置正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我在一个子域(dev.u413.com)上有一个网站,我使用jquery向另一个子域(api.u413.com)上的JSON api发出ajax请求。当我检查Chrome开发工具和Firefox Firebug中的请求时,我的请求被 Access-Control-Allowed-Origin 阻止。我将 document.domain 设置为当前域的后缀: document.domain ='u413.com';

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';.

这是我的要求:

    $.ajax({
        dataType: 'json',
        data: { parseAsHtml: true, cli: 'help' },
        url: 'http://api.u413.com/',
        success: function (response) {
            alert(response.Command);
        }
    });

如果我将ajax请求修改为在同一个域上,则请求成功。

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);
        }
    });

为什么会发生这种情况?浏览器不应该抱怨跨域问题,因为根据 document.domain 设置为两个子域的公共后缀, https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript>相同来源政策

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.

我目前正在使用jsonp应用程式,但我觉得正确的ajax请求应该按照我上面链接的同源策略工作。我宁愿不使用jsonp,如果我不必。是否不可能在子域之间定期发出ajax请求?

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 无法使用AJAX。它用于跨域iframe和窗口通信。在您的情况下,您违反了相同的来源政策(表格的最后一行),因此您需要使用JSONP或服务器侧桥。

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.

这是一个非常 nice guide ,说明了实现跨网域AJAX请求的不同技术。

Here's a very nice guide which illustrates different techniques for achieving cross domain AJAX requests.

这篇关于跨子域名ajax请求被拒绝,即使document.domain设置正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆