XMLHttpRequest:请求的资源上没有“Access-Control-Allow-Origin”标头

时间:2017-08-10 10:21:02

标签: javascript ajax cors

我的jQuery AJAX方法在从另一个域请求时工作正常,但我的纯JavaScript XMLHttpRequest会抛出上述错误。为什么呢?

AJAX:

$.ajax({
    url: url,
    data: {
        email: email
    },
    success: function(data) {
        console.log(data);
    }
});

Pure JavaScript:

var invocation = new XMLHttpRequest();
function myRequest(){
  if(invocation) {
    invocation.open('GET', url, true);
    invocation.onreadystatechange = function(){
        if (invocation.readyState == invocation.DONE && invocation.status == 200){
            console.log(invocation.responseText);
        }
    }
    invocation.send(); 
  }
}
myRequest();

我当然在服务器端设置Access-Control-Allow-Origin: *

修改

以下是完整的服务器端代码:

public function my_event() {
    header("Access-Control-Allow-Origin: *");
    $result = "hi";
    return json_encode($result);
}

编辑2

以下是请求标头:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Host:example.com
Origin:example.com
Pragma:no-cache
Referer:example.com/cors-test
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

以下是回复标题:

Connection:close
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Thu, 10 Aug 2017 10:32:37 GMT
Location:example.com/api_handler
Server:Apache
Set-Cookie:DYNSRV=lin-10-140-0-32; path=/

0 个答案:

没有答案