標籤:style blog http java color 使用
首先處理伺服器代碼,使返回的資料符合特定的格式,為了方便這裡使用了php
test.php代碼如下
1 <?php 2 $con = mysql_connect("localhost","root","root"); 3 mysql_select_db("test", $con); 4 5 $result = mysql_query("select username,password from user"); 6 while ($row = mysql_fetch_array($result)) { 7 $com[] = $row; 8 } 9 10 $callback = $_GET["jsonpcallback"];11 $json=json_encode($com);12 echo $callback.‘(‘."$json".‘)‘;13 ?>
$json的輸出值為[{"0":"1","username":"1","1":"1","password":"1"},{"0":"admin","username":"admin","1":"1","password":"1"}],是一個標準的json,但這個頁面需要處理跨域,所以需要把json包裹成callback([{"0":"1","username":"1","1":"1","password":"1"},{"0":"admin","username":"admin","1":"1","password":"1"}])的格式輸出給瀏覽器
html代碼如下
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>Insert title here</title> 6 <script src="js/jquery.min.js" type="text/javascript"></script> 7 <script> 8 $(function(){ 9 var URL="http://localhost/test.php";10 $.ajax({11 type : ‘GET‘,12 url : URL,13 dataType : ‘jsonp‘,14 jsonp : ‘jsonpcallback‘,15 success : function(data) {16 alert(JSON.stringify(data));17 }18 });19 });20 </script>21 </head>22 </html>
輸出結果
jsonp只支援"GET"的請求,這是載入跨域資料的原理決定的,雖然jquery使用了$.ajax()函數擷取資料,但是jsonp擷取資料真正做法並不是ajax,而是使用動態載入js的方式。