【问题标题】:Vanilla ES6 aJax call Unexpected tokenVanilla ES6 aJax 调用 Unexpected token
【发布时间】:2017-05-18 11:05:06
【问题描述】:

尝试从服务器返回一些 JSON 代码,以便我可以在 JavaScript 中对其进行操作。

但是我收到以下错误:

未捕获的 SyntaxError:JSON 中第 10 位的意外标记 m

这是我的代码:

getJSON(url, success) {
      let query = [ 'cars', 'vans', 'bikes' ];

      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            success(JSON.parse(xhr.responseText));
          } else {
            exit(xhr.responseText);
          }
        }
      };
      xhr.open('GET', url);
      xhr.send();
    }

如果我只是 console.log xhr.responseText,这就是我得到的响应:

[
  {
    make: 'VOLVO'
  },
  {
    make: 'AUDI'
  },
  {
    make: 'VOLKSWAGON'
  },
]

【问题讨论】:

  • 这不是有效的 JSON。 JSON 不能有尾随逗号,并且总是需要对属性名称和字符串使用双引号。
  • 废话,我的错。我搞砸了 JSON
  • 您可能希望捕获错误以便在服务器返回无效数据时优雅地失败。
  • 您需要将字符串用引号括起来。您的 "make" 键缺少开头引号,这就是控制台告诉您的内容。它期待",但它找到了m。投票结束,因为这是一个数据问题,而不是编码问题。

标签: javascript ajax


【解决方案1】:

您尝试解析的对象是有效的 JavaScript 对象,但不是有效的 JSON。

keys 应该是字符串,定义为

零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义

您不应使用任何尾随逗号(请参阅Can you use a trailing comma in a JSON object?)。

您的对象的正确 JSON 字符串应该是:

let s = '[ {"make": "VOLVO"}, {"make": "AUDI"}, {"make": "VOLKSWAGON"} ]';

可以修复代码以检测此问题:

getJSON(url, success) {
    let query = [ 'cars', 'vans', 'bikes' ];
    let xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    let parsedJSON = JSON.parse(xhr.responseText);
                    success(parsedJSON);
                } catch (e) {
                    if (e instanceof SyntaxError === true) {
                        // Problem with the format of the JSON string.
                    } else {
                        // Other error
                    }
                }
            } else {
                exit(xhr.responseText);
            }
        }
    };

    xhr.open('GET', url);
    xhr.send();
}

杂项。资源:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2019-08-05
    • 2016-10-15
    相关资源
    最近更新 更多