直接在后端加上
header("Allow-Control-Allow-Origin:允许跨域的域名(实际开发中不建议使用*)")如果需要前后端跨域session共享那么前端的请求应该加上
xhrFields:{
withCreadentials:true
}
$.ajax({
url:url,
<! -- 加上此部分 Start-- >
xhrFields: {
withCredentials: true
},
crossDomain: true,
<! -- 加上此部分 End-- >
success:function() {
},
error:function() {
}
});后端应该加上header("Access-Control-Allow-Credentials:true");
header("Access-Control-Allow-Origin:http://mymyjd.cn");//注意修改这里填写你的前端的域名
header("Access-Control-Max-Age:3600");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');但是仅仅这样只能实现简单请求的跨域,对于复杂请求如put Delete 请求还没有找到最优的解决方法备注如果使用think PHP5.1框架的话,就不用自己写header
并且复杂请求的问题得到解决
解决方法如下
使用路由
如果某个路由或者分组需要支持跨域请求,可以使用
Route::get('new/:id', 'News/read')
->ext('html')
->allowCrossDomain();跨域请求一般会发送一条 OPTIONS 的请求,一旦设置了跨域请求的话,不需要自己定义 OPTIONS请求的路由,系统会自动加上。
跨域请求系统会默认带上一些Header,包括:
Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE
Access-Control-Allow-Headers:Authorization, Content-Type, If-Match, If-Modified-Sinc
e, If-None-Match, If-Unmodified-Since, X-Requested-With你可以添加或者更改Header信息,使用Route::get('new/:id', 'News/read')
->ext('html')
->header('Access-Control-Allow-Origin','thinkphp.cn')
->header('Access-Control-Allow-Credentials', 'true')
->allowCrossDomain(); 最佳答案