1、JSONP是一个非官方的协议,它允许在服务器端集成script tags返回至客户端,通过javascript callback的形式实现跨域访问。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
document.getElementById('btnOk').onclick = function () {
//创建一对script标签
var jsonp = document.createElement('script');
//指定加载的域上的资源
jsonp.src = 'http://www.bbb.com/index.php?fn=callback&_='+new Date().getTime();
//将标签加入到head标签中
document.getElementsByTagName('head')[0].appendChild(jsonp);
}
};
//处理函数
function callback( msg ) {
alert(msg.name + ":" + msg.age);
}
</script>
</head>
<body>
<input type="button" id="btnOk" value="确定">
</body>
</html>
<?php
//生成数组数据
$data = array(
'name' => 'lisi',
'age' => 20
)
//生成json字符串
$str = json_encode( $data );
//获取回调函数名称
$fn = $_GET['fn'];
//输出结果,执行客户端js函数
echo $fn.'('.$str.')';
2、JQ解决跨域问题
支持 $.ajax() $.get() $.getJSON()
/*JQ解决跨域问题*/
$.ajax({
type : 'get',
url : 'http://www.bb.com/demo.php',
dataType : 'jsonp',
jsonp : 'fn',
success : function (msg) {
alert(msg.name + ':' + msg.age);
}
});
$.get('http://www.bb.com/demo.php?fn=?',function (msg) {
alert(msg.name);
});
$.getJSON('http://www.bb.com/demo.php?fn=?',function (msg) {
alert(msg.name);
});
<?php
//生成数组数据
$data = array(
'name' => 'lisi',
'age' => 20
)
//生成json字符串
$str = json_encode( $data );
//获取回调函数名称
$fn = $_GET['fn'];
//输出结果,执行客户端js函数
echo $fn.'('.$str.')';
3、axios 解决跨域
// 继承
Vue.prototype.$http = axios;
// 实例化
var vm = new Vue({
el: '#box',
data: {
},
created: function () {
// console.log(111);
this.hello();
},
methods: {
hello: function () {
this.$http.get('http://localhost:3000/axios?cb=cb', {
// withCredentials:true
}).then(function (data, msg) {
console.log(data);
console.log(msg);
}).
catch (function (err) {
console.log(err);
})
}
}
})
参考链接:
JQ: http://www.runoob.com/json/json-jsonp.html
axios: http://cnodejs.org/topic/5930430f03dba3510d8a62c6