Jsonp 跨域的原理以及Jquery的解决方案

转自:http://www.cnblogs.com/DanielChow/archive/2010/05/17/1737070.html

 

原理:JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。

个人理解:

     就是在客户端动态注册一个函数function a(data),然后将函数名传到服务器,服务器返回一个a({/*json*/})到客户端运行,这样就调用客户端的function a(data),从而实现了跨域.

<! DOCTYPE html PUBLIC  " -//W//DTD XHTML Transitional//EN "   " http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd " >   
< html xmlns = " http://www.worg/xhtml "   >   
< head >   
    
< title > Test Jsonp < / title>  
     < script src = " http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js "  type = " text/javascript " >< / script>      
     < script type = " text/javascript " >   
            
function   jsonpCallback (result)   
            {              
                 $.each(result.items, 
function (i,item){
                       $(
" <img/> " ).attr( " src " , item.media.m).appendTo( " body " );
                       
if  ( i  ==   3  )  return   false ;
                 });  
            }   
        
< / script>
< / head>  
< body >   
< script type = " text/javascript "  src = " http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json& jsoncallback=jsonpCallback " >< / script>   
< / body>  
< / html>

 

jQuery的解决方案:

<! DOCTYPE html PUBLIC  " -//W//DTD XHTML Transitional//EN "   " http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd " >   
< html xmlns = " http://www.worg/xhtml "   >   
< head >   
    
< title > Test Jsonp < / title>  
     < script src = " http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js "  type = " text/javascript " >< / script>      
     < script type = " text/javascript " >
        $(
function () {
            
$.getJSON( " http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json& jsoncallback=? " function (data) {
                $.each(data.items, 
function (i, item) {
                    $(
" <img/> " ).attr( " src " , item.media.m).appendTo( " body " );
                    
if  (i  ==   3 return   false ;
                });
            });
        });        
    
< / script>
< / head>  
< body >< / body>  
< / html>

 

jquery 的jsoncallback是动态生成的,真正请求服务器的地址:http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=jsonp1274058545738

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值