web前端|js教程
Cookie,Ajax,ie
web前端-js教程ajax跨域访问,可以使用jsonp方法或设置Access-Control-Allow-Origin实现,关于设置Access-Control-Allow-Origin实现跨域访问可以参考之前我写的文章《ajax 设置Access-Control-Allow-Origin实现跨域访问》
彩虹授权源码使用,vscode代码提示功能,ubuntu显存测试,tomcat整个启动流程,爬虫取证,php 时间验证码,哈尔滨seo关键词,手机网站源码如何安装软件,focus模板下载lzw
1.ajax跨域访问,cookie丢失
工作室源码,vscode上怎么编译c语言,ubuntu连接无线网络,tomcat底层语言,c sqlite读取,有创意的网页设计,asp读取服务器时间,timeline 插件,前端框架分享,图片爬虫搜索,安卓php环境,深圳煌盛seo,springboot灵活列表,织梦网站修改教程视频,手机网页背景特效下载,css制作登陆页面模板,网站后台 竖着 导航菜单,考试页面html模板下载地址,asp人事档案管理系统,ios 关闭程序 代码lzw
首先创建两个测试域名
快递在线下单源码,UBUNTU手机支架可爱,tomcat插件打war包,夏天 小黑爬虫,php类面试题,seo出品lzw
作为客户端域名
作为服务端域名
测试代码
setcookie.PHP 用于设置服务端cookie
server.php 用于被客户端请求
true, ame => $name, cookie => isset($_COOKIE[data])? $_COOKIE[data] : \);// 指定允许其他域名访问header(Access-Control-Allow-Origin:);// 响应类型header(Access-Control-Allow-Methods:POST); // 响应头设置header(Access-Control-Allow-Headers:x-requested-with,content-type);header(content-type:application/json);echo json_encode($ret);?>
test.html 客户端请求页面
首先先执行/setcookie.php, 创建服务端cookie。
然后执行/test.html
输出
{"success":true,"name":"fdipzone","cookie":""}
获取cookie失败。
2.解决方法
客户端
请求时将withCredentials属性设置为true
使可以指定某个请求应该发送凭据。如果服务器接收带凭据的请求,会用下面的HTTP头部来响应。
服务端
设置header
header("Access-Control-Allow-Credentials:true");
允许请求带有验证信息
test.html 修改如下
server.php 修改如下
true, ame => $name, cookie => isset($_COOKIE[data])? $_COOKIE[data] : \);// 指定允许其他域名访问header(Access-Control-Allow-Origin:);// 响应类型header(Access-Control-Allow-Methods:POST); // 响应头设置header(Access-Control-Allow-Headers:x-requested-with,content-type);// 是否允许请求带有验证信息header(Access-Control-Allow-Credentials:true);header(content-type:application/json);echo json_encode($ret);?>
按之前步骤执行,请求返回
{"success":true,"name":"fdipzone","cookie":"1484558863"}
获取cookie成功
3.注意事项
1.如果客户端设置了withCredentials属性设置为true,而服务端没有设置Access-Control-Allow-Credentials:true,请求时会返回错误。
XMLHttpRequest cannot load /server.php. Credentials flag is rue, but the Access-Control-Allow-Credentials header is \. It must be rue to allow credentials. Origin \ is therefore not allowed access.
2.服务端header设置Access-Control-Allow-Credentials:true后,Access-Control-Allow-Origin不可以设为*,必须设置为一个域名,否则回返回错误。
XMLHttpRequest cannot load /server.php. A wildcard * cannot be used in the Access-Control-Allow-Origin heade
下面看下Ajax跨域请求COOKIE无法带上的解决办法
原生ajax请求方式:
var xhr = new XMLHttpRequest(); xhr.open("POST", "/demo/b/index.php", true); xhr.withCredentials = true; //支持跨域发送cookiesxhr.send();
jquery的ajax的post方法请求:
$.ajax({ type: "POST", url: "/api/test", dataType: jsonp, xhrFields: {withCredentials: true }, crossDomain: true, success:function(){ }, error:function(){ }})
服务器端设置:
header("Access-Control-Allow-Credentials: true");header("Access-Control-Allow-Origin: ");