关于CORS(跨源资源共享)实践

打开页面 http://www.yangyueyuan.com/home/account/login
在控制台发送跨域ajax请求:
$.ajax({
type:"get",
url:"http://tdcCenterManage.dev/index.php?abc=1",/*url写异域的请求地址*/
dataType:"json",/*加上datatype*/
success:function(){
  
}
});

http://tdcCenterManage.dev/index.php:

这个请求的响应header如下:

HTTP/1.1 200 OK
Date: Mon, 03 Jul 2017 03:57:09 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Content-Length: 7
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
这个请求能正常发送,但是根据响应header浏览器报错:

login:1 XMLHttpRequest cannot load http://tdccentermanage.dev/index.php?abc=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.yangyueyuan.com' is therefore not allowed access.

http://tdcCenterManage.dev/index.php中加入header头:

header("Access-Control-Allow-Origin:*");
// 星号表示所有的域都可以接受,
header("Access-Control-Allow-Methods:GET,POST");
echo 'success';

再发送相同的ajax请求,就不报错了,响应头如下:

HTTP/1.1 200 OK
Date: Mon, 03 Jul 2017 03:56:46 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST
Content-Length: 7
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

可以看到响应头多了两行。

CORS 背后的基本思想,就是使用自定义的HTTP 头部
让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。




你可能感兴趣的:(php)