jsonp理解
jsonp理解
一.jsonp是什么?
jsonp是一种非官方的跨域请求协议,通俗的说就是数据交互的方法,他解决了ajax不能跨域请求的困境。他与json完全不是一回事,json是一种数据传输的格式,jsonp是传输的渠道
二.原理
1.我们在使用javascript的引入外部js文件时,<script>标签有个src的属性,用于引入外部的.js文件。我们在使用的时候,这个src的文件路径可以是本域名下的,也可以是其他网站上的,这就为跨域创造条件。
2.javascript又可以创建元素,操作元素。这样我们就可以使用js动态的创建<scrpit>标签,然后添加src属性,这样他就会使用get方法请求路径。利用这个请求原理,可以在客户端定义一个带参数函数,然后在服务器端返回 调用客户端函数的字符串,这样数据就参数的形式被传回了客户端。
原理图解:
3.原理代码的简单实现(摘自于:木子月)
<script>
创建并且插入script标签
function createscript(reqUrl){
var Ocreatescript = document.createElement('script');
Ocreatescript .type = 'text/javascript';
Ocreatescript.src = reqUrl;
document.getElementsByTagName('head')[0].appendChild(Ocreatescript);
}
创建一个hello方法
function hello(res){
console.log(res);
}
createscript('http://loveme.com/index.php?callback=hello ');
请求回来的内容:
hello({ 'hi': 'nihao' }); //调用了上面的hello方法
</script>
服务端:index.php
<?php
$a=$_GET["callback"];
echo $a.'({ 'hi': 'nihao' })'
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript" src=jquery.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", async: false, url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", dataType: "jsonp", jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 success: function(json){ alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。'); }, error: function(){ alert('fail'); } }); }); </script> </head> <body> </body> </html>