JSONP是JSON格式的另一種使用方式,最主要的目的是要從另一個網域取得資料。

舉裡來說:

網站1:test1.test.com

網站2:test2.demo.com

當網站2需要和網站1共用同一個會員帳號的時候,這時候就必須使用JSONP的方式來傳值。

 

那麼JSONP怎麼使用 ?  下面是以PHP來當做實例:

 

 ///   首先準備好要做轉換的資料

    $jsonp_data = array();

    $jsonp_data['account'] = "newaurora";

    $jsonp_data['uname'] = "Stanley";

 

///  將資料(陣列、變數)轉成json格式

    $content = json_encode($jsonp_data); 

 

///  改變格式

    $jsondata = "data(".$content.");";

 

///  輸出

    print_r($jsondata);

    //如果使用變數的話只需使用

    //echo $jsondata;

 

以上只是先由PHP端產生JSONP的資料

接下來的步驟則是接收JSONP的資料

 

 在接收端的網頁寫入讀取php的javascript程式

<script>

var data = function(jsonpdata){

      var user =data.account ;    //讀取account索引的值

      alert(user);                      //檢查值是否正確

};

//  呼叫剛剛寫的php程式

var url = "http://網址/jsonp.php";

var script = document.createElement('script');

script.setAttribute('src',url);

document.getElementsByTagName('head')[0].appendChild(script);

</script>

 

把以上javascript程式寫道接收端的網頁就大功告成了

 

如果覺得對你有幫助的話. 請幫小弟按個讚吧~ 

 

其他相關文章參考:

如何使用AJAX傳值 

使用 AJAX 記錄點擊次數 

 

arrow
arrow

    newaurora 發表在 痞客邦 留言(0) 人氣()