三、jsonp的原理:带有src属性标签的跨域资源获取能力,在jsonp中通常使用<script>标签,因为<script>标签获取的跨域资源可以使用回调函数直接处理
jsonp的实现:
前端代码:
<script>
function callback(data){
console.log(data);
}
</script>
<script type="text/javascript" src="//www.remote.com/remote.php?callback=callback"></script>
后台代码 <www.remote.com/remote.php>
if(isset($_GET["callback"])){
$server_name = $_SERVER["SERVER_NAME"];
$path = $_SERVER["PHP_SELF"];
$query_string = $_SERVER["QUERY_STRING"];
if($query_string!=""&&$query_string!=null){
$query_paras = explode("&", $query_string);
$query_array = array();
$query_length = count($query_paras);
for($i=0;$i<$query_length;$i++){
$paras = explode("=", $query_paras[$i]);
$query_array[$paras[0]]=$paras[1];
}
$data = array("server_name"=>$server_name,"path"=>$path,"query_paras"=>$query_array);
}else{
$data = array("server_name"=>$server_name,"path"=>$path);
}
$callback = $_GET["callback"];
echo $callback . "(" . json_encode($data) . ")";
后台服务器将需要返回的json数据进行封装,然后并不直接返回json,而是返回一句js代码,
echo $callback . "(" . json_encode($data) . ")";
这句代码将返回的json数据调用回调函数直接进行处理
四、zepto实现jsonp
function getData(){
$.ajax({
type: 'GET',
url: '//www.homeworksong.sinaapp.com/getUrlInfo.php?callback=?',
timeout: 300,
context: $('tbody'),
data: { name: 'Zepto',type:"JSONP" },
success: function(data){
console.log(data);
},
error: function(xhr, type){
alert('Ajax error!')
}
});
}
五、kissy实现jsonp
require(["io","node","util"],function(IO,$,Util){
IO.jsonp("http://www.homeworksong.sinaapp.com/getUrlInfo.php",{type:"JSONP",name:"Kissy" },function(data){
console.log(data);
});
});
});