好的,所以我正在尝试从包含几个 LED 等状态的 json 文件中提取数据。我有一个每秒运行几次并提取数据并在网页加载它的脚本。问题是,服务器读取 json 文件大约 20 次后,最终会抛出这个错误。
SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束
// For toggling the LED/switch status indicators using the json data
$(document).ready(function() {
(function worker() {
$.ajax({
url: 'server_info.json',
success: function(data) {
var json = $.parseJSON(data);
console.log(json);
if (json.led_1 == "off") {
// do stuff
}
if (json.led_2 == "off") {
// do stuff
}
if (json.led_3 == "off") {
// do stuff
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 250);
}
});
})();
});
json 文件如下所示:
{ "led_1": "on", "led_2": "on", "led_3": "on" }
在我看来,json 数据的格式总是正确的。我不明白错误来自哪里。有任何想法吗?
原文由 z470 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 Firefox 调试,当我收到该错误时,我能够看到返回的值类型是未定义的。首先检查要解析的值是否为空/未定义,然后如果条件为假,则继续解析,否则处理条件解决了我的问题。