JSONP跨域請求資料報錯 “Unexpected token :”的解決辦法

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   java   on   檔案   資料   

本地虛擬兩個網域名稱,分別為:www.test.com、www.abc.com

http://www.test.com/index.html頁面點擊按鈕,請求返回www.abc.com網域名稱目錄下的檔案的資料,其代碼為:

<!DOCTYPE html><html><head>  <meta charset="utf-8" />  <title>JSONP跨域請求</title>  <script src="http://www.oschina.net/js/2012/jquery-1.7.1.min.js" type="text/javascript"></script>  <script type="text/javascript">  $(function(){      $(".button").on("click",function(){        $.ajax({          type:"get",          url:"http://www.abc.com/json.php",          dataType:"jsonp",          jsonp:"callback",          jsonpCallback:"success_jsonpCallback",          success:function(json){            $(".user").html("使用者資訊:"+json.username+","+json.age+","+json.gender);          },          error:function(){            alert("請求出錯!");          }        });      });  });  </script></head><body>  <button class="button">點擊擷取資料</button>   <div class="user"></div></body></html>


http://www.abc.com/json.php檔案代碼為:

<?php $arr = array (‘username‘=>‘jack‘,‘age‘=>21,‘gender‘=>‘male‘); echo json_encode($arr);?>


在Chrome瀏覽器調試會發現報錯了,

json.php返回的資料確實是json類型的資料 {"username":"jack","age":21,"gender":"male"} ,問題處在哪?

翻看了一下Jquery文檔發現jsonp:"callback", jsonpCallback:"success_jsonpCallback",傳遞這兩個參數是有原因的,jsonp的返回資料格式應該是: “用戶端傳遞的回調方法名稱(json資料)”,將php檔案改為:

<?php $arr = array (‘username‘=>‘jack‘,‘age‘=>21,‘gender‘=>‘male‘); echo $_GET[‘callback‘]."(".json_encode($arr).")";?>


測試,正確返回結果,如:


可以看到,php檔案返回的結果是 success_jsonpCallback({"username":"jack","age":21,"gender":"male"}) ,這才是正確的jsonp返回格式,而success_jsonpCallback這是傳遞過去的參數。


JSONP跨域請求資料報錯 “Unexpected token :”的解決辦法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.