使用jquery實現跨域請求資料

來源:互聯網
上載者:User

標籤: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的方式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.