我在我的MooTools脚本中运行一个AJAX调用,这在Firefox中工作得很好,但在Chrome中,我得到了一个未捕获的SyntaxError:意外令牌:错误,我不能确定为什么。注释掉代码来确定坏代码在哪里不会产生任何结果,我认为这可能是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();
  });
});

当前回答

当你的数据返回错误的json格式时出现“Uncaught SyntaxError: Unexpected token”错误,在某些情况下,你不知道你得到了错误的json格式。 请用alert()检查;函数

onSuccess : function(resp){  
   alert(resp);  
}

你收到的信息应该是:{"firstName":"John", "lastName":"Doe"} 然后您可以使用下面的代码

onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}

“未捕获SyntaxError:意外令牌” 但如果json格式有误 例:

...{“firstName”:“约翰”,“姓”:“母鹿”}

or

Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}

所以你得到了错误的json格式,请在json .decode或json .parse之前修复它

其他回答

在我的情况下,我遇到了同样的错误,而运行spring mvc应用程序由于错误的映射在我的mvc控制器

@RequestMapping(name="/private/updatestatus")

我把上面的映射改为

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

我也遇到了同样的问题,结果是Json从服务器返回 不是有效的Json-P。如果不使用跨域调用,请使用常规Json。

我得到这个错误,因为我在脚本标签中缺少类型属性。

最初我使用,但当我在脚本标记内添加类型属性时,我的问题就解决了

未捕获的SyntaxError:意外的令牌}

Chrome给了我这个示例代码的错误:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

并解决了它,固定的onclick就像

... onclick="window.location = '?dir=zzz'" ...

但是这个错误和这个问题无关。

在我的例子中,把/放在脚本的src或样式表的href的开头就解决了这个问题。