getJSON跨域SyntaxError问题分析
昨天写一个功能:点击手机验证的同时获取json端的数据。
javascript代码如下:
$(".check_mobile").click(function(){
varmobile=$('.mobile').val();
$.getJSON("http://www.test.com/user.php?mobile="+mobile+"&format=json&jsoncallback=?",function(data){
if(data.succ==1){
varhtml="<inputtype='hidden'name='cityid'value='"+data.data.cityid+"'><inputtype='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
);
}
echojson_encode($return);
}
?>
相应如下:
问题出来了:
在火狐浏览器中:SyntaxError:missing;beforestatement
解决方法如下:
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");代码,则会出现
XMLHttpRequestcannotload''.No'Access-Control-Allow-Origin'headerispresentontherequestedresource.Origin''isthereforenotallowedaccess.
如果少了echo"{$_GET['jsoncallback']}({$b})";代码
在谷歌浏览器中:UncaughtSyntaxError:Unexpectedtoken:
在火狐浏览器中:SyntaxError:missing;beforestatement
热门推荐
10 高考送考祝福语简短
11 奶奶生日感恩祝福语简短
12 5岁宝宝祝福语简短
13 家长祝福语大全简短内容
14 春天变冷祝福语简短
15 长辈钻石婚祝福语简短
16 写给老师祝福语简短大学
17 姥爷生日诗句祝福语简短
18 新春进门祝福语大全简短