【问题标题】:Why am I getting Access-Control-Allow-Origin error when trying to use ajax to access a page?为什么在尝试使用 ajax 访问页面时出现 Access-Control-Allow-Origin 错误?
【发布时间】:2011-05-19 11:45:58
【问题描述】:

我正在尝试使用 ajax 从我希望能够在任何地方运行的脚本访问我网站上的一些数据。我脚本中的 ajax 代码看起来像这样

var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://mywebsite.com/page?i=2&json', true);
ajax.onreadystatechange = function() {
  if (ajax.status == 200) {
    console.log(JSON.parse(ajax.responseText));
  }
  else
    console.log('Could not connect.');
}
ajax.send();

但是当我运行它时,我得到了错误

XMLHttpRequest 无法加载 http://mywebsite.com/page?i=2&json。 来源http://anotherwebsite.com 是 不允许 访问控制允许来源。

在我网站上的脚本中,页面内有以下几行,

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

但我仍然遇到同样的错误。我希望我网站上的那个页面可以通过 ajax 从 Internet 上的任何其他页面访问,因为我的脚本是一个可以在任何网站上使用的扩展。

编辑: 好的,如果我将 ajax 对象上的 'withCredentials' 属性设置为 true,并且在我的服务器上将 Access-Control-Allow-Credentials 标头设置为 true,我就可以正常工作了。然后使用我的脚本,我还传递了域,因此它可以在我的服务器脚本上的 Access-Control-Allow-Origin 中返回。通配符 * 不起作用。到目前为止,这仅在 Chrome 中进行了测试。

【问题讨论】:

    标签: javascript ajax same-origin-policy


    【解决方案1】:

    大多数浏览器不会让您执行跨域 ajax,因此您可以做的是调用本地服务器端脚本,该脚本生成跨域 ajax 并将答案返回给您的 javascript。 我听说它被命名为“代理脚本”,是我所知道的唯一可靠的解决方案。

    step 1: javascript on otherdomain.com --GET--> server-side script on otherdomain.com
    step 2: server-side script on otherdomain.com --GET--> mywebsite.com/page?i=2&json
    step 3: mywebsite.com/page?i=2&json --JSON--> server-side script on otherdomain.com
    step 4: server-side script on otherdomain.com --JSON--> javascript on otherdomain.com
    

    【讨论】:

    • 我不能这样做,因为 otherdomain.com 不是我的域,它可以是任何域,因为它是一个扩展。
    • ——但是有问题的浏览器会,否则它不会给出那个错误。
    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 2017-12-29
    • 2018-01-26
    • 2013-10-30
    • 2017-06-15
    • 2017-12-30
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多