我目前正在努力使用从服务器应用程序收到的JSON字符串。
这是接收JSON字符串的JavaScript代码段:
var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);
connection.onmessage = function (e) {
console.log('Received from server: ', e.data);
var response = JSON.parse(e.data);
if(response.action=="networks") {
console.log('SSID: ', response.ssid);
}
};
我根据上面的console.log
调用在浏览器控制台中收到此回复:
Received from server: {"action":"networks","ssid":"UPC6288862","rssi":-69,"enc":8}
结束以下错误:
Uncaught SyntaxError: Unexpected token in JSON at position 60
at JSON.parse (<anonymous>)
at WebSocket.connection.onmessage (WebSocket.js:19)
connection.onmessage@WebSocket.js:19
当我手动将字符串放入JSON.parse()时,如下所示:
var data = JSON.parse('{"action":"networks","ssid":"UPC Wi-Free","rssi":-42,"enc":255}');
解析有效,我可以通过response.action
访问字段。
但为什么我会收到错误? e.data
不是正确的字符串,还是我需要在解析之前添加一些引号或类似e.data
?
更新:
以下是通过WebSocket.js接收JSON字符串时Chrome网络标签的屏幕截图: