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

來源:互聯網
上載者:User
原文  http://www.cnphp6.com/archives/65409

Jquery使用ajax方法實現jsonp跨域請求資料的時候報錯 “Uncaught SyntaxError: Unexpected token :”,主要問題在於返回的資料格式不正確

本地虛擬兩個網域名稱,分別為: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這是傳遞過去的參數 。



重點是主三個參數:

dataType:"jsonp",          jsonp:"callback",          jsonpCallback:"success_jsonpCallback",

樣本:

    $.ajax({
type : "POST",
url : domain+"/member_login.action",
data : {
loginName:username,
password:password,
apptype:2
},
dataType: "jsonp",
            jsonp: "callback",//傳遞給請求處理常式或頁面的,用以獲得jsonp回呼函數名的參數名(一般預設為:callback)
            jsonpCallback:"flightHandler",//自訂的jsonp回呼函數名稱,預設為jQuery自動產生的隨機函數名,也可以寫"?",jQuery會自動為你處理資料
   //contentType: "application/json;charset=UTF-8",        //傳值方式
async : true,
success : function(msg) {
                alert(msg);
                alert(msg.member.memberName);
                console.log(msg);
 if(msg==""){
   alert("帳號密碼錯誤。登入失敗!");                 
 }else{
     
 }
}
});



sevlet端寫法:

response.getWriter().append("flightHandler("+jsonString+")");

聯繫我們

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