jsonp跨域访问

js/ajax跨越访问—jsonp的原理和实例(javascript和jquery)


什么是JSONP协议?

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

很明显,JSONP是一种脚本注入(Script Injection)行为,需要特别注意其安全性。


Jquery中的jsonp实例

我们需要两个页面,分别承担协议的客户端和服务器端角色。

客户端代码:

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02  <html xmlns="http://www.w3.org/1999/xhtml" >
03  <head>
04      <title>jsonp测试例子</title>
05       <script type="text/javascript" src="http://www.xuejiehome.com/js/jquery.min.js"></script>
06       <script type="text/javascript">
07      jQuery(document).ready(function(){
08         $.ajax({
09              type: "get",
10              async: false,
11              url: "http://www.xuejiehome.com/demos/jsonp.php",
12              dataType: "jsonp",
13              jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
14              jsonpCallback:"feedBackState",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
15              success: function(data){
16                  var $ul = $("<ul></ul>");
17                  $.each(data,function(i,v){
18                      $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
19                  });
20                  $("#remote").append($ul);
21              },
22              error: function(){
23                  alert('fail');
24              }
25          });
26      });
27      </script>
28      </head>
29   <body>
30   远程数据如下:<br/>
31   <div id="remote"></div>
32   </body>
33  </html>

服务端代码(本例采用PHP):

1 <?php
2 $jsonp $_REQUEST["callback"];
3 $str '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';
4 $str $jsonp "(" .$str.")";
5 echo $str;
6 ?>

效果演示:

 

Jsonp的原理和简单实例

jquery是对其进行了封装,你可能看不到真正的实现方法,我们用下面的一个例子进行说明:

客户端代码:

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02  <html xmlns="http://www.w3.org/1999/xhtml" >
03  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
04  <head>
05      <title>jsonp测试例子</title>
06      <script type="text/javascript" src="http://www.xuejiehome.com/js/jquery.min.js"></script>
07      <script type="text/javascript">
08      function CallJSONPServer(url){                                 // 调用JSONP服务器,url为请求服务器地址   
09         var oldScript =document.getElementById(url);       // 如果页面中注册了调用的服务器,则重新调用
10         if(oldScript){
11         oldScript.setAttribute("src",url);
12         return;
13         }
14         var script =document.createElement("script");       // 如果未注册该服务器,则注册并请求之
15         script.setAttribute("type", "text/javascript");
16         script.setAttribute("src",url);
17         script.setAttribute("id", url);
18         document.body.appendChild(script);
19     }
20     
21     function OnJSONPServerResponse(data){
22         var $ul = $("<ul></ul>");
23         $.each(data,function(i,v){
24             $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
25         });
26         $("#remote").append($ul);
27     }
28      </script>
29      </head>
30   <body>
31   <input type="button" value="点击获取远程数据" onclick="CallJSONPServer('http://www.xuejiehome.com/demos/jsonp_original.php')" />
32   <div id="remote"></div>
33   </body>
34  </html>

服务端代码:

1 <?php
2 $str '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';
3 $str "OnJSONPServerResponse(" .$str.")";
4 echo $str;
5 ?>

效果展示:

 

别的不多说,相信看代码大家应该明白它是怎么实现的了。


需要注意:


1.由于 jquery 在ajax 处理中使用的是utf-8编码传递参数的,所以jsonp处理端用utf-8的编码最好,这样省得编码转换了,如果不是utf-8记得转换,否则中文会乱码。

2.请求的服务端url最好不要写成http://www.xuejiehome.com/?act=add这样的,应写全其为:http://www.xuejiehome.com/index.php?act=add这样的,在应用的过程中出现了不兼容的情况。

3.如果同一个页面使用多个jsonp的请求,需要让jsonpCallback:"feedBackState"中的feedBackState这个函数名字不一样,或者不写,默认使用jquery自动生成的随机函数。否则某个请求将会错误。

jsonpCallback:为jsonp请求指定一个回调函数名。这个值将用来取代jQuery自动生成的随机函数名。这主要用来让jQuery生成独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。我想应该是因为生成名字一样冲突的问题导致的。


原文地址http://www.xuejiehome.com/blread-1627.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值