我在我的MooTools脚本中运行一个AJAX调用,这在Firefox中运行良好,但在Chrome中我得到一个 "Uncaught SyntaxError:Unexpected token :" 错误,我无法确定原因。我想可能是返回的JSON有问题,所以把代码注释出来以确定坏代码的位置。在控制台检查,我看到返回的JSON是这样的。
{"votes":47,"totalvotes":90}
我没有看到任何问题,为什么会出现这种错误?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
这种情况刚刚发生在我身上,原因不是上面的原因。我使用jQuery命令getJSON,并添加callback=?
以使用JSONP(因为我需要跨域),并返回JSON代码{"foo":"bar"}
,得到错误。
这是因为我应该包括回调数据,如jQuery17209314005577471107_1335958194322({"foo":"bar"})
。
以下是我用来实现这一目标的PHP代码,如果使用JSON(没有回调),它就会退化。
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
希望这能对未来的人有所帮助。
我刚刚解决了这个问题。有一些东西导致了标准Request调用的问题,所以这是我使用的代码。
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
如果有人知道为什么标准请求对象会给我带来问题,我很想知道。