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了,如有朋友碰到什么問題可發上來大家共同交流。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM