z47*_*470 11 html javascript jquery json
好的,所以我试图从一个保存了几个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);
}
});
})();
});
Run Code Online (Sandbox Code Playgroud)
json文件如下所示:
{ "led_1": "on", "led_2": "on", "led_3": "on" }
Run Code Online (Sandbox Code Playgroud)
在我看来,json数据总是正确格式化.我不知道错误来自哪里.有任何想法吗?
使用"dataType"设置来标识响应的类型,以便.ajax()调用知道其JSON并且不需要猜测.
这可能无法解决问题,因为很可能您的响应没有为抛出错误的调用返回JSON.如果添加错误设置,您可以看到服务器在出错时返回的内容,但如果请求完成,请检查控制台以查找从服务器返回的内容.正如我所说,如果你从$ .parseJSON()开始收到错误,它可能不是JSON.
$(document).ready(function() {
(function worker() {
$.ajax({
url: 'server_info.json',
dataType: 'json',
success: function(data) {
console.log(data);
if (data.led_1 == "off") {
// do stuff
}
if (data.led_2 == "off") {
// do stuff
}
if (data.led_3 == "off") {
// do stuff
}
},
error: function( data, status, error ) {
console.log(data);
console.log(status);
console.log(error);
}
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 250);
}
});
})();
});
Run Code Online (Sandbox Code Playgroud)
事实证明,该错误与 JSON 无关。这实际上是因为后端返回的是非 JSON 或空字符串。
// Update
if(updateFile($id,$author)) {
echo json_encode(
array('message' => 'Post Updated')
);
} else {
echo json_encode(
array('message' => 'Post Not Updated')
);
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这有效。祝你好运
| 归档时间: |
|
| 查看次数: |
61858 次 |
| 最近记录: |