Analysis of getJSON cross domain SyntaxError problem

  • 2021-07-10 19:09:03
  • OfStack

Yesterday, I wrote a function: Click on the mobile phone to verify and get the data of json.

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);
}
});
});

The code for user. php is as follows:


<?php
if($_GET){
$mobile = $_GET['mobile'];
if ($mobile == 'XXXX') {
$user = array(
'city' =>' Shijiazhuang ',
'cityid' =>'1',
'community' =>' Amethyst Yuecheng ',
'communityid'=>'1'
);
$sucess = 1;
$return = array(
'succ' =>$sucess,
'data' => $user
);
}else {
$sucess = 2;
$return = array(
'succ' =>$sucess
);
}
echo json_encode($return);
}
?>

The corresponding is as follows:

Here's the problem:

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;

The final complete code:


<?php
header("Access-Control-Allow-Origin:http:www.test.com");
if($_GET){
$mobile = $_GET['mobile'];
if ($mobile == '18831167979') {
$user = array(
'city' =>' Shijiazhuang ',
'cityid' =>'1',
'community' =>' Amethyst Yuecheng ',
'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 header is missing from PHP ("Access-Control-Allow-Origin: http: www. test. com"); Code, the

XMLHttpRequest cannot load ''. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ' is therefore not allowed access.
If echo is missing "{$_ GET ['jsoncallback']} ({$b})"; Code

In Google Browser: Uncaught SyntaxError: Unexpected token:
In Firefox: SyntaxError: missing; before statement


Related articles: