2

我正在尝试使用 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。Access-Control-Allow-Origin 不允许来源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 中进行了测试。

4

1 回答 1

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
于 2010-12-03T01:54:48.843 回答