getJSON跨域SyntaxError問題分析
昨天寫一個功能:點擊手機驗證的同時獲取json端的數(shù)據(jù)。
javascript代碼如下:
$(".check_mobile").click(function(){ var mobile = $('.mobile').val(); $.getJSON("http://www.test.com/user.php?mobile="+mobile+"&format=json&jsoncallback=?", function(data){ if (data.succ == 1) { var html = "<input type='hidden' name='cityid' value='"+data.data.cityid+"'><input type='hidden' name='communityid' value='"+data.data.communityid+"'>"; $(".r_m").append(html); } }); });
user.php代碼如下:
<?php if($_GET){ $mobile = $_GET['mobile']; if ($mobile == 'XXXX') { $user = array( 'city' =>'石家莊', 'cityid' =>'1', 'community' =>'紫晶悅城', 'communityid'=>'1' ); $sucess = 1; $return = array( 'succ' =>$sucess, 'data' => $user ); }else { $sucess = 2; $return = array( 'succ' =>$sucess ); } echo json_encode($return); } ?>
相應如下:
問題出來了:
在火狐瀏覽器中: SyntaxError: missing ; before statement
解決方法如下:
header("Access-Control-Allow-Origin:http:www.test.com"); $b = json_encode($return); echo "{$_GET['jsoncallback']}({$b})"; exit;
最后完整代碼:
<?php header("Access-Control-Allow-Origin:http:www.test.com"); if($_GET){ $mobile = $_GET['mobile']; if ($mobile == '18831167979') { $user = array( 'city' =>'石家莊', 'cityid' =>'1', 'community' =>'紫晶悅城', 'communityid'=>'1' ); $sucess = 1; $return = array( 'succ' =>$sucess, 'data' => $user ); }else { $sucess = 2; $return = array( 'succ' =>$sucess ); } $b = json_encode($return); echo "{$_GET['jsoncallback']}({$b})"; exit; } ?>
如果在 PHP 中少了 header("Access-Control-Allow-Origin:http:www.test.com"); 代碼,則會出現(xiàn)
XMLHttpRequest cannot load ''. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ' is therefore not allowed access.
如果少了 echo "{$_GET['jsoncallback']}({$b})"; 代碼
在谷歌瀏覽器中:Uncaught SyntaxError: Unexpected token :
在火狐瀏覽器中:SyntaxError: missing ; before statement
相關文章
Yii 訪問 Gii(腳手架)時出現(xiàn) 403 錯誤
這篇文章主要介紹了Yii 訪問 Gii(腳手架)時出現(xiàn) 403 錯誤的解決方法的相關資料,需要的朋友可以參考下2018-06-06php的curl攜帶header請求頭信息實現(xiàn)http訪問的方法
這篇文章主要介紹了php的curl攜帶header請求頭信息實現(xiàn)http訪問的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01Swoole?webSocket客服IM消息系統(tǒng)方案解析
這篇文章主要為大家介紹了Swoole?webSocket客服IM消息系統(tǒng)方案解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03