通过JSONP实现JQuery跨域

    技术2025-10-24  27

    什么是JSONP

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

    对于上面的解释,我们可以简单这样理解:JSONP就是可以通过JavaScript 文件进行跨域通讯的方式。 注意:JSONP 服务器端代码需要充分做好安全 措施。

    最简单的JSONP

    var JSONP = document.createElement("script") ; //FF:onload IE:onreadystatechange JSONP.onload = JSONP.onreadystatechange = function(){ //onreadystatechange,仅IE if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") { alert($("#demo").html()); JSONP.onload = JSONP.onreadystatechange = null//请内存,防止IE memory leaks } } JSONP.type = "text/javascript"; JSONP.src = "http://a.pojaaimg.cn/2010/js/jquery.js"; //在head之后添加js文件 document.getElementsByTagName("head")[0].appendChild(JSONP);

    JSONP实例

    我们可以首先定义一个函数来执行JSONP返回的数据,然后通过JSONP的src传此函数给后台,进行处理,返回可执行的函数。例如下面代码:

    function jsonpHandle(a){ alert(a); } var JSONP = document.createElement("script") ; JSONP.type = "text/javascript"; JSONP.src = "http://www.js8.in/jsonp.php?callback=jsonpHandle"; //在head之后添加js文件 document.getElementsByTagName("head")[0].appendChild(JSONP);

    后台jsonp.php的代码:

    echo $_GET["callback"]."('hello,world')";

            JQuery与PHP整合实例

            jQuery $.ajax()支持get方式的跨域,这其实是采用jsonp的方式来完成的.

            1.client.html(客户端文件)

          <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf8" /> <mce:script language="javascript" src="jquery-1.4.js" mce_src="jquery-1.4.js"></mce:script> <mce:script type="text/javascript"><!-- $(document).ready(function (){ $('#latest').click(function (){ var $limit=$('#limit').attr('value'); var $category=$('#category').attr('value'); $.getJSON("http://localhost/wordpress/rpc/server.php?limit="+$limit+"&category="+$category+"&callback=?", function(data){ // 往后台传递的参数 $rpc = "日志链接:"+data.link1+"<br> 日志标题:"+data.title1; $('#result').html($rpc); //调用用来显示内容的div }) }) }); // --></mce:script> </head> <body> <div id="result" style="background:orange;border:1px solid red;width:300px;height:200px;"></div> <form id="formtest" action="" method="post">   <p><span>日志数:</span><input type="text" name="limit" id="limit" size="15" ></p> <p><span>日志分类:</span><input type="text" name="category" id="category" size="15" ></p> </form> </body> <button id="latest">最新日志</button> </html>

          2.server.php(用来处理客户端发来的请求)

          <?php //header('Content-Type: application/json; charset=utf-8'); require_once("../wp-config.php"); $limit=$_REQUEST['limit']; //接收客户端发来的数据 $category=$_REQUEST['category']; $arr=Array(); function my_wp_get_archives($limit) { $show_post = "type=postbypost&echo=0&limit=".$limit; return wp_get_archives($show_post); //调用wordpress自身的函数 } $posts=split('<li>',my_wp_get_archives($limit)); for($start=1;$start<sizeof($posts);$start++) { $arr["title".$start]=strip_tags($posts[$start]); //对从wordpress取到的数据进行处理,提取出字符串,方便自己加工成Json数据 $arr["link".$start]=substr($posts[$start],strpos($posts[$start],'=/'')+2,strpos($posts[$start],'//'')-8); } // var_dump($arr); $json = json_encode($arr); //用Json_encode函数处理php的数组 echo $_GET['callback']."(".$json.")"; ?>

    最新回复(0)