Home >Backend Development >PHP Tutorial >GetJSON cross-domain SyntaxError problem analysis, getjsonsyntaxerror_PHP tutorial
Yesterday I wrote a function: click on the mobile phone to verify and get the data on the json side at the same time.
The javascript code is as follows:
$(".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 code is as follows:
<?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); } ?>
Correspondingly as follows:
The problem is:
In Firefox: SyntaxError: missing ; before statement
The solution is as follows:
header("Access-Control-Allow-Origin:http:www.test.com"); $b = json_encode($return); echo "{$_GET['jsoncallback']}({$b})"; exit;
Final complete code:
<?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; } ?>
If the header("Access-Control-Allow-Origin:http:www.test.com"); code is missing in PHP,
will appearXMLHttpRequest cannot load ''. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ' is therefore not allowed access.
If there is missing echo "{$_GET['jsoncallback']}({$b})"; code
In Google Chrome: Uncaught SyntaxError: Unexpected token :
In Firefox: SyntaxError: missing ; before statement
In actual website use, it should be said that it is impossible to achieve cross-domain access with pure js. Don't believe some misleading information on the Internet. The reason why we emphasize the condition of "in actual website use" is because IE browser will give Local static web pages have higher permissions and can access any website asynchronously, but it will not work if you put it into a real domain-owned website application. Cross-domain requires the server to act as a proxy, so the essence of cross-domain is actually "pseudo-cross-domain", which is somewhat misleading for those who are new to ajax. If you believe that js can cross-domain, you will go astray.
Based on security considerations
Jquery cannot use this kind of cross-domain.
getjson needs to return callback