首页 技术 正文
技术 2022年11月6日
0 收藏 807 点赞 789 浏览 1297 个字

Ajax跨域方法有多种 这里介绍CROS跨域的实际案例

场景:A域名 请求 B域名;

暂且 A为客户端 B为服务端;

请求的服务端必须自己能控制 或者服务器端头部已经添加 Access-Control-Allow-Origin :允许你 的域名

服务端:

header("Access-Control-Allow-Origin:http://www.xxxx.com");
header("Access-Control-Allow-Method:POST,GET,OPTIONS");
header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Credentials: true');
Access-Control-Allow-Origin 未允许跨域请求的ip或地址
Access-Control-Allow-Method 请求方式
Access-Control-Allow-Headers 支持的头信息字
Access-Control-Allow-Credentials 要想发送Cookie 这个配置必须为true服务端实现以上配置,客户端基本上可以跨域请求了客户端:
$.ajax({
url: B域名,
dataType: 'json',
data: {username:username,password: password},
contentType: 'application/json; charset=utf-8',
type: 'get',
withCredentials: true,
async:true,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
xhrFields:{
withCredentials:true
},
success: function(result){
console.log(result);
if(result.type == 'success'){
window.location.href='http://we.lb.com/web/'+result.redirect;
}
},
error: function(error){
console.log(error);
},
});
                beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},这个设置是请求头部信息X-Requested-With:XMLHttpRequest,在我的项目里没添加这个 服务端识别不了ajax请求;若能识别忽悠就可以
                xhrFields:{
withCredentials:true
},这个设置withCredentials:true, 如果发送Cookie 这个配置必须要有;参照:http://www.ruanyifeng.com/blog/2016/04/cors.html
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,484
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,899
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,732
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,485
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,125
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,285