Javascript:意外的令牌ILLEGAL

时间:2011-08-09 14:39:39

标签: javascript jquery webkit

我在Chrome中遇到错误Uncaught SyntaxError: Unexpected token ILLEGAL

代码是

$("form#new_redemption").live('submit', function() {
  event.preventDefault();
  var that    = $(this);

  var action  = that.attr('action');
  var data    = that.serialize();

  $.ajax({
    type: "POST",
    url:  action,
    data: data,
    dataType: 'json',
    beforeSend: function(request) {
      request.setRequestHeader("Accept", "application/json");
    },
    success: function(res) {
      var response = JSON.parse(res.responseText); // <~~~ Unexpected token ILLEGAL
      if (response.message) {
        that.slideUp();
        $("#results").html(response.message).attr('class', 'notice').slideDown();
      }
      else if (response.url) {
        window.location = response.url 
      }
    },
    error: function(res) {
      var response = JSON.parse(res.responseText);
      $('#results').html(response.error).attr('class', 'error').slideDown();
    }
  });
  return false;
});

在出错时,此代码效果很好。但每次成功回复我都会收到错误。这里有问题吗? VIM中有没有办法在代码中突出显示非法的javascript字符?

谢谢!

2 个答案:

答案 0 :(得分:2)

dataType设置为json会在success回调中自动为您解析响应JSON。

试试这个:

$("form#new_redemption").live('submit', function() {
  event.preventDefault();
  var that    = $(this);

  var action  = that.attr('action');
  var data    = that.serialize();

  $.ajax({
    type: "POST",
    url:  action,
    data: data,
    dataType: 'json',
    beforeSend: function(request) {
      request.setRequestHeader("Accept", "application/json");
    },
    success: function(res) {
      if (response.message) {
        that.slideUp();
        $("#results").html(response.message).attr('class', 'notice').slideDown();
      }
      else if (response.url) {
        window.location = response.url 
      }
    },
    error: function(res) {
      var response = JSON.parse(res.responseText);
      $('#results').html(response.error).attr('class', 'error').slideDown();
    }
  });
  return false;
});

答案 1 :(得分:0)

要扩展上面的其中一条评论,我收到此错误是因为正在返回的JSON结果中存在问题。具体来说,JSON响应数据中的一个字符串值中有一个无标题的双引号。在我的情况下,这是我自己调用的Ajax函数,所以我要做的就是在返回JSON数据之前逃避服务器上的双引号。然后我发现我对换行符有同样的问题,所以我使用了另一篇文章中的str_replace调用: PHP's json_encode does not escape all JSON control characters

function escapeJsonString($value) {
    # list from www.json.org: (\b backspace, \f formfeed)    
    $escapers =     array("\\",     "/",   "\"",  "\n",  "\r",  "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t",  "\\f",  "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}