服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - getJSON跨域SyntaxError问题分析

getJSON跨域SyntaxError问题分析

2020-07-21 14:45PHP编程技术网 PHP教程

这篇文章主要介绍了getJSON跨域SyntaxError问题分析,需要的朋友可以参考下

昨天写一个功能:点击手机验证的同时获取json端的数据。

javascript代码如下:

?
1
2
3
4
5
6
7
8
9
$(".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代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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

解决方法如下:

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

最后完整代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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"); 代码,则会出现

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

延伸 · 阅读

精彩推荐