getJSON跨域SyntaxError問題分析,getjsonsyntaxerror_PHP教程

來源:互聯網
上載者:User

getJSON跨域SyntaxError問題分析,getjsonsyntaxerror


昨天寫一個功能:點擊手機驗證的同時擷取json端的資料。

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 = "";$(".r_m").append(html);}});});

user.php代碼如下:

<?phpif($_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);}?>

相應如下:

問題出來了:

在Firefox瀏覽器中: SyntaxError: missing ; before statement

解決方案如下:

header("Access-Control-Allow-Origin:http:www.test.com");$b = json_encode($return);echo "{$_GET['jsoncallback']}({$b})";exit;

最後完整代碼:

<?phpheader("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"); 代碼,則會出現

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})"; 代碼

在Google瀏覽器中:Uncaught SyntaxError: Unexpected token :
在Firefox瀏覽器中:SyntaxError: missing ; before statement


為何我用getJSON也不可以跨域,,

在實際的網站運用中,純js實現跨域訪問應該說是不可能的,不要相信網上的一些誤導,之所以要強調是“在實際的網站運用中”的條件,是因為IE瀏覽器會給本地的靜態網頁較高的許可權,可以非同步訪問任何網站,但是如果你把它放到真實的有域歸屬的網站運用中就不行了。跨域是需要伺服器端充當代理的,所以跨域的本質其實是“偽跨域”,這對剛接觸ajax的朋友來說有一定的誤導性,相信js可以跨域,那你就誤入歧途了
 

jquery跨域訪問的問題以及getjson的使用Ajax

基於安全考慮
Jquery 是不能採用這種跨域的.
getjson需要返回callback
 

http://www.bkjia.com/PHPjc/860468.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/860468.htmlTechArticlegetJSON跨域SyntaxError問題分析,getjsonsyntaxerror 昨天寫一個功能:點擊手機驗證的同時擷取json端的資料。 javascript代碼如下: $(".check_mobile")....

  • 聯繫我們

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