jsonp

跨域实现的两种方式
一、通过src=”http://romateServer.com/api?callback=callbackHandler”
回调成功后,在浏览器端实现callbackHandler方法,返回值在callbackHandler参数中
批注:既然如此,所有src都可以实现跨域。比如图片src等。具体实现是将该内容动态的插入到DOM中。

二、通过jQuery的ajax参数{dataType:jsonp,jsonp:callback,success:function(){}}
回调成功后,返回值在success参数中

在jQuery1.5后,又增加如下描述,照着做之后发现报错:
Uncaught SyntaxError: Unexpected token :
暂未找到解决办法,所以还是回归传统方式。

jsonp
Type: String
Override the callback function name in a JSONP request. This value will be used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url. So {jsonp:’onJSONPLoad’} would result in ‘onJSONPLoad=?’ passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the “?callback” string to the URL or attempting to use “=?” for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: “callbackName” }
jsonpCallback
Type: String or Function()
Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it’ll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

ajax与jsonp的异同再做一些补充说明:
1、ajax和jsonp这两种技术在调用方式上“看起来”很像,目的也一样,都是请求一个url,然后把服务器返回的数据进行处理,因此jquery和ext等框架都把jsonp作为ajax的一种形式进行了封装;

2、但ajax和jsonp其实本质上是不同的东西。ajax的核心是通过XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加

1. <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />  
    2. <script type="text/javascript">  
    3.     function jsonpCallback(result) {  
    4.         //alert(result);  
    5.         for(var i in result) {  
    6.             alert(i+":"+result[i]);//循环输出a:1,b:2,etc.  
    7.         }  
    8.     }  
    9.     var JSONP=document.createElement("script");  
    10.     JSONP.type="text/javascript";  
    11.     JSONP.src="http://crossdomain.com/services.php?callback=jsonpCallback";  
    12.     document.getElementsByTagName("head")[0].appendChild(JSONP);  
    13. </script>  

Html代码

1. <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />  
    2. <script type="text/javascript">  
    3.     function jsonpCallback(result) {  
    4.         alert(result.a);  
    5.         alert(result.b);  
    6.         alert(result.c);  
    7.         for(var i in result) {  
    8.             alert(i+":"+result[i]);//循环输出a:1,b:2,etc.  
    9.         }  
    10.     }  
    11. </script>  
    12. <script type="text/javascript" src="http://crossdomain.com/services.php?callback=jsonpCallback"></script>  

注意:JavaScript的链接,必须在function的下面。

(2)服务器端:

Php代码

1. <?php  
    2.   
    3. //服务端返回JSON数据  
    4. $arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
    5. $result=json_encode($arr);  
    6. //echo $_GET['callback'].'("Hello,World!")';  
    7. //echo $_GET['callback']."($result)";  
    8. //动态执行回调函数  
    9. $callback=$_GET['callback'];  
    10. echo $callback."($result)";  

jQuery中的实现

如果将上述JS客户端代码用jQuery的方法来实现,也非常简单。

$.getJSON 
$.ajax 
$.get 

(1)$.getJSON
Js代码

    1. <script type="text/javascript" src="jquery.js"></script>  
    2. <script type="text/javascript">  
    3.     $.getJSON("http://crossdomain.com/services.php?callback=?",  
    4.     function(result) {  
    5.         for(var i in result) {  
    6.             alert(i+":"+result[i]);//循环输出a:1,b:2,etc.  
    7.         }  
    8.     });  
    9. </script>  

(2)$.ajax
Js代码

1. <script type="text/javascript" src="jquery.js"></script>  
    2. <script type="text/javascript">  
    3.     $.ajax({  
    4.         url:"http://crossdomain.com/services.php",  
    5.         dataType:'jsonp',  
    6.         data:'',  
    7.         jsonp:'callback',  
    8.         //jsonpCallback:"flightHandler",//可选,jQuery把返回放到success里了。默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据  
    9.         success:function(result) {  
    10.             for(var i in result) {  
    11.                 alert(i+":"+result[i]);//循环输出a:1,b:2,etc.  
    12.             }  
    13.         },  
    14.         timeout:3000  
    15.     });  
    16. </script>  

(3)$.get
Js代码

1. <script type="text/javascript" src="jquery.js"></script>  
    2. <script type="text/javascript">  
    3.     $.get('http://crossdomain.com/services.php?callback=?', {  
    4.         name: encodeURIComponent('tester')  
    5.     }, function (json) {   
    6.         for(var i in json) alert(i+":"+json[i]);   
    7.     }, 'jsonp');  
    8. </script>  

其中 jsonCallback 是客户端注册的,获取跨域服务器上的json数据后,回调的函数。
http://crossdomain.com/services.php?callback=jsonpCallback
这个 url 是跨域服务 器取 json 数据的接口,参数为回调函数的名字,返回的格式为
jsonpCallback({msg:’this is json data’})

后台Java的做法:
获取jsonp中定义的参数,然后返回:
String jsonpcallback = request.getParameter(‘jsonpcallback’);
response.write(jsonpcallback + “({msg:’sucess’})”);
前台接受到如下jQuery171047328996332362294_1458195688979({msg:’logout success.’})

使用JSON的优点在于:
比XML轻了很多,没有那么多冗余的东西。
JSON也是具有很好的可读性的,但是通常返回的都是压缩过后的。不像XML这样的浏览器可以直接显示,浏览器对于JSON的格式化的显示就需要借助一些插件了。
在JavaScript中处理JSON很简单。
其他语言例如PHP对于JSON的支持也不错。
JSON也有一些劣势:
JSON在服务端语言的支持不像XML那么广泛,不过JSON.org上提供很多语言的库。
如果你使用eval()来解析的话,会容易出现安全问题。
尽管如此,JSON的优点还是很明显的。他是Ajax数据交互的很理想的数据格式。

缺点与不足:
JSONP 是构建 mashup 的强大技术,但不幸的是,它并不是所有跨域通信需求的万灵药。它有一些缺陷,在提交开发资源之前必须认真考虑它们。

第一,也是最重要的一点,没有关于 JSONP 调用的错误处理。如果动态脚本插入有效,就执行调用;如果无效,就静默失败。失败是没有任何提示的。例如,不能从服务器捕捉到 404 错误,也不能取消或重新开始请求。不过,等待一段时间还没有响应的话,就不用理它了。(未来的 jQuery 版本可能有终止 JSONP 请求的特性)。

JSONP 的另一个主要缺陷是被不信任的服务使用时会很危险。因为 JSONP 服务返回打包在函数调用中的 JSON 响应,而函数调用是由浏览器执行的,这使宿主 Web 应用程序更容易受到各类攻击。如果打算使用 JSONP 服务,了解它能造成的威胁非常重要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值