这里总结两个跨域访问的方法
1. jsonp
普通 js 实现
前端直接将访问路径写在 script 标签的路径中,get 变量带着调用后的回调函数名,服务器处理后,以 “回调函数名(返回数据)” 的格式返回,回调函数真正接受到的数据为真正的返回数据,并不带有回调函数名及其他。要注意的是 jsonp 的方法只能使用 get 方法传递变量。
服务器端代码
<?php
header('Content-type: application/json');
$callbackFunction = $_REQUEST['jsoncallback'];
echo $callbackFunction . "(" . json_encode(['111','222']) . ")";
// 返回格式: back(['111','222'])
浏览器端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsonp 实例</title>
<script>
function back(returnData, method) {
console.log(returnData);
}
</script>
<!-- jsoncallback 变量为返回时调用的 js 函数 -->
<script src="http://www.test.com/index.php?jsoncallback=back"></script>
</head>
<body>
</body>
</html>
jQuery实现
原理与 js 实现相同,只是前端实现代码不同。
浏览器端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsonp 实例</title>
<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
<script>
function back(returnData, method) {
console.log(returnData);
}
$.ajax({
url:"http://www.test.com/index.php",
dataType: "jsonp",
jsonp: "jsoncallback", // 带有回调函数值的变量名称
jsonpCallback: "back", // 毁掉函数名
success: function (data) {
alert(123);
}
})
</script>
</head>
<body>
</body>
</html>
2. cors
cors 相比于 jsonp 方法传送变量的方法更多,具体有哪些见参考文件,这里面只是描述了最简单的使用方法。
浏览器端将 ajax 的 withCredentials 属性打开,否则浏览器不会发送 cookie,同时也不会接收和处理服务器发过来的 cookie。
服务器端要设置头部属性
Access-Control-Allow-Origin 允许接收的域名
Access-Control-Allow-Credentials 设置允许接收与发送 cookie
Access-Control-Expose-Headers 可选字段,可以拿到扩展字段,具体见参考文件。
浏览器端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsonp 实例</title>
<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
<script>
function back(returnData, method) {
console.log(returnData);
}
$.ajax({
url:"http://www.test.com/index.php",
dataType: "json",
success: function (data) {
alert(data);
},
xhrFields: {
withCredentials: true,
}
})
</script>
</head>
<body>
</body>
</html>
服务器端代码
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://www.blog.com');
echo json_encode(['111','222']);
这里的 cors 只实现了简单请求
jsonp 与 cors 的区别
cors 相比于 jsonp 更灵活,cors 可以有多种传值方式,而 jsonp 只能用 get 来传值。
jsonp 所有浏览器都支持cors ,不支持 IE10 以下的浏览器。
参考资料: