什么是JSONP协议?
JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。
很明显,JSONP是一种脚本注入(Script Injection)行为,需要特别注意其安全性。
Jquery中的jsonp实例
我们需要两个页面,分别承担协议的客户端和服务器端角色。
客户端代码:
04 | < title >jsonp测试例子</ title > |
06 | < script type = "text/javascript" > |
07 | jQuery(document).ready(function(){ |
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) |
20 | $("#remote").append($ul); |
31 | < div id = "remote" ></ div > |
服务端代码(本例采用PHP):
2 | $jsonp = $_REQUEST [ "callback" ]; |
3 | $str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]' ; |
4 | $str = $jsonp . "(" . $str . ")" ; |
效果演示:
Jsonp的原理和简单实例
jquery是对其进行了封装,你可能看不到真正的实现方法,我们用下面的一个例子进行说明:
客户端代码:
03 | < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> |
05 | < title >jsonp测试例子</ title > |
07 | < script type = "text/javascript" > |
08 | function CallJSONPServer(url){ // 调用JSONP服务器,url为请求服务器地址 |
09 | var oldScript =document.getElementById(url); // 如果页面中注册了调用的服务器,则重新调用 |
11 | oldScript.setAttribute("src",url); |
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); |
21 | function OnJSONPServerResponse(data){ |
22 | var $ul = $("< ul ></ ul >"); |
23 | $.each(data,function(i,v){ |
24 | $("< li />").text(v["id"] + " " + v["name"]).appendTo($ul) |
26 | $("#remote").append($ul); |
32 | < div id = "remote" ></ div > |
服务端代码:
2 | $str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]' ; |
3 | $str = "OnJSONPServerResponse(" . $str . ")" ; |
效果展示:
别的不多说,相信看代码大家应该明白它是怎么实现的了。
需要注意:
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