开发者

Why am I getting Access-Control-Allow-Origin error when trying to use ajax to access a page?

开发者 https://www.devze.com 2023-01-28 11:30 出处:网络
I\'m 开发者_Go百科trying to use ajax to access some data on my website from a script that I want to be able to run anywhere. The ajax code from my script looks something like this

I'm 开发者_Go百科trying to use ajax to access some data on my website from a script that I want to be able to run anywhere. The ajax code from my script looks something like this

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

But when I run it I get the error

XMLHttpRequest cannot load http://mywebsite.com/page?i=2&json. Origin http://anotherwebsite.com is not allowed by Access-Control-Allow-Origin.

On the script on my website I have the following lines inside of page,

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

But I still get the same error. I want that page on my website to be accessable from any other page on the Internet via ajax, because my script is an extension that should be usable on any website.

EDIT: Ok I got this working if I set the 'withCredentials' attribute on the ajax object to true and on my server send back Access-Control-Allow-Credentials header set to true. Then with my script I also passed the domain so it can be returned in Access-Control-Allow-Origin on my server script. The wildcard * didn't work. This is only tested in Chrome so far.


Most browsers won't let you do cross-domain ajax, so what you could do is to make a call to a local server-side script that makes the cross-domain ajax and gives the answer back to your javascript. I heard of it named as "proxy-script" and is the only reliable solution I know.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号