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

阅读原文:http://www.xuejiehome.com/blread-1627.html

很庆幸,我又见到了末日后新升的太阳,所以我还能在这里写文章,言归正传哈,最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用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这样的,在应用的过程中出现了不兼容的情况。

到此就ok了,如有朋友碰到什么问题可发上来大家共同交流。

posted @ 2012-12-25 16:07  雪洁  阅读(7236)  评论(5编辑  收藏  举报