淺析php中jsonp的跨域實例

參考 :http://lunzi.iteye.com/blog/1962283javascript

http://blog.csdn.net/json_ligege/article/details/51098993php

          

咱們如今www.test.com這個域名下面有這麼個html文件testjsonp.html:html

複製代碼代碼以下:java


<!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>Untitled Page</title>
      <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){ 
        $.ajax({
             type: "GET",
             async: false,
             //url: "http://test/jsonp.php",
             url:"http://mytaobao.com/jsonp.php",
             dataType: "jsonp",
             jsonp: "callback",//傳遞給請求處理程序或頁面的,用以得到jsonp回調函數名的參數名(通常默認爲:callback)
             jsonpCallback:"flightHandler",//自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名,也能夠寫"?",jQuery會自動爲你處理數據
             success: function(json){
                 alert('您查詢到航班信息:票價: ' + json.price + ' 元,餘票: ' + json.tickets + ' 張。回調函數名爲: '+json.func);
             },
             error: function(){
                 alert("fail");
             }
         });
     });
     </script>
     </head>
  <body>
  </body>
 </html>jquery


注意,要真正運行上面的代碼可能須要jquery的文件,你能夠將<script type="text/javascript" src="jquery-1.7.2.min.js"></script>改成你目錄中jquery的文件路徑:
如:<script type="text/javascript" src="js/jquery.js"></script>
而後,你能夠再找個另一個域名的web目錄,將文件jsonp.php:web

複製代碼代碼以下:ajax


<?php
$callback = $_GET["callback"];
$a = array(
 'code'=>'CA1998',
    'price'=>'6000',
    'tickets'=>20,
    'func'=>$callback,
);
$result = json_encode($a);
echo "flightHandler($result)";
exit;json


放到這個目錄下面去。這樣就能夠測試了。 
直接在瀏覽器訪問testjsonp.html.就能夠看到效果了。瀏覽器

相關文章
相關標籤/搜索