Home > php教程 > php手册 > getJSON跨域SyntaxError问题分析,getjsonsyntaxerror

getJSON跨域SyntaxError问题分析,getjsonsyntaxerror

WBOY
Release: 2016-06-13 09:27:30
Original
1470 people have browsed it

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 = "<input type='hidden' name='cityid' value='"+data.data.cityid+"'><input type='hidden' name='communityid' value='"+data.data.communityid+"'>";
$(".r_m").append(html);
}
});
});
Copy after login

user.php代码如下:

<&#63;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);
}
&#63;>
Copy after login

相应如下:

问题出来了:

在火狐浏览器中: SyntaxError: missing ; before statement

解决方法如下:

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

最后完整代码:

<&#63;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;
}
&#63;>
Copy after login

如果在 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

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

在实际的网站运用中,纯js实现跨域访问应该说是不可能的,不要相信网上的一些误导,之所以要强调是“在实际的网站运用中”的条件,是因为IE浏览器会给本地的静态网页较高的权限,可以异步访问任何网站,但是如果你把它放到真实的有域归属的网站运用中就不行了。跨域是需要服务器端充当代理的,所以跨域的本质其实是“伪跨域”,这对刚接触ajax的朋友来说有一定的误导性,相信js可以跨域,那你就误入歧途了
 

jquery跨域访问的问题以及getjson的使用Ajax

基于安全考虑
Jquery 是不能采用这种跨域的.
getjson需要返回callback
 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template