利用script标签的src属性来实现跨域请求(JSONP协议)

什么是JSONP协议?
JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。
很明显,JSONP是一种脚本注入(Script Injection)行为,需要特别注意其安全性。
 
Jquery中的jsonp实例
 
我们需要两个页面,分别承担协议的客户端和服务器端角色。
 
客户端代码:
 
 
<!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>jsonp测试例子</title>
       <script type= "text/javascript" src= "http://www.yzswyl.cn/js/jquery.min.js" ></script>
       <script type= "text/javascript" >
      jQuery(document).ready(function(){
         $.ajax({
              type: "get" ,
              async: false ,
              url: "http://www.yzswyl.cn/demos/jsonp.php" ,
              dataType: "jsonp" ,
              jsonp: "callback" , //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
              jsonpCallback: "feedBackState" , //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
              success: function(data){
                  var $ul = $( "<ul></ul>" );
                  $.each(data,function(i,v){
                      $( "<li/>" ).text(v[ "id" ] + " " + v[ "name" ]).appendTo($ul)
                  });
                  $( "#remote" ).append($ul);
              },
              error: function(){
                  alert( 'fail' );
              }
          });
      });
      </script>
      </head>
   <body>
   远程数据如下:<br/>
   <div id= "remote" ></div>
   </body>
  </html>
 
服务端代码(本例采用PHP):
 
 
<?php
$jsonp = $_REQUEST[ "callback" ];
$str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]' ;
$str = $jsonp . "(" .$str. ")" ;
echo $str;
?>
 
效果演示:
 
 
 
Jsonp的原理和简单实例
 
jquery是对其进行了封装,你可能看不到真正的实现方法,我们用下面的一个例子进行说明:
 
客户端代码:
 
 
<!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" >
  <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" />
  <head>
      <title>jsonp测试例子</title>
      <script type= "text/javascript" src= "http://www.yzswyl.cn/js/jquery.min.js" ></script>
      <script type= "text/javascript" >
      function CallJSONPServer(url){                                 // 调用JSONP服务器,url为请求服务器地址   
         var oldScript =document.getElementById(url);       // 如果页面中注册了调用的服务器,则重新调用
         if (oldScript){
         oldScript.setAttribute( "src" ,url);
         return ;
         }
         var script =document.createElement( "script" );       // 如果未注册该服务器,则注册并请求之
         script.setAttribute( "type" , "text/javascript" );
         script.setAttribute( "src" ,url);
         script.setAttribute( "id" , url);
         document.body.appendChild(script);
     }
 
     function OnJSONPServerResponse(data){
         var $ul = $( "<ul></ul>" );
         $.each(data,function(i,v){
             $( "<li/>" ).text(v[ "id" ] + " " + v[ "name" ]).appendTo($ul)
         });
         $( "#remote" ).append($ul);
     }
      </script>
      </head>
   <body>
   <input type= "button" value= "点击获取远程数据" onclick= "CallJSONPServer('http://www.yzswyl.cn/demos/jsonp_original.php')" />
   <div id= "remote" ></div>
   </body>
  </html>
 
服务端代码:
 
<?php
$str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]' ;
$str = "OnJSONPServerResponse(" .$str. ")" ;
echo $str;
?>
效果展示:
 
 
 
别的不多说,相信看代码大家应该明白它是怎么实现的了。
 
需要注意:
 
1.由于 jquery 在ajax 处理中使用的是utf-8编码传递参数的,所以jsonp处理端用utf-8的编码最好,这样省得编码转换了,如果不是utf-8记得转换,否则中文会乱码。
 
2.请求的服务端url最好不要写成http: //www.yzswyl.cn/?act=add这样的,应写全其为:http://www.yzswyl.cn/index.php?act=add这样的,在应用的过程中出现了不兼容的情况。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值