jsonp的原理
jsonp可以解决跨域问题
// 浏览器阻止的ajax的跨域,但是没有阻止html标签请求外部资源的跨域
// fn();
document.onclick = function(){
var url = “http://localhost/1910-server/jsonp/data/jsonp3.php”;
jsonp(url,function(res){
alert(res)
},{
user:“admin”,
pass:123,
// 根据后台指定的字段名,传入回调函数名,传给后台
zxc:“ewqrwer213213213”,
// 用来保存后台接收的 回调函数名所在的字段名,传给自己的函数
columnName:“zxc”
})
}
function jsonp(url,callback,data){
// 解析要发送的数据
data = data || {};
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
// 将数据拼接到url
url = url + "?" + str.slice(0,str.length-1);
// jsonp的功能:1.创建script
var script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
// jsonp的功能:2.创建准备被资源执行的全局函数
window[data[data.columnName]] = function(res){
callback(res);
}
}
<?php $u = @$_GET["user"]; $p = @$_GET["pass"]; $cb = @$_GET["zxc"]; $data = "hello,这是接收到的jsonp的数据:".$u."===".$p; echo $cb."('".$data."')"; ?>