Javascript - JSON.parse: 数据意外结束 - 使用有效 JSON 时出错。我究竟做错了什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9321510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - JSON.parse: unexpected end of data - Error when using valid JSON. What am I doing wrong?
提问by douggard
So, I've found similar questions about JQuery in which you do not need to parse. Since I am using the AJAX XMLHttpRequest, from what I understand, the parse is necessary. The error is given on the line:
因此,我发现了有关 JQuery 的类似问题,您无需在其中进行解析。由于我使用的是 AJAX XMLHttpRequest,据我所知,解析是必要的。该行给出了错误:
text = JSON.parse(jsonGet.responseText);
Error:
错误:
JSON.parse: unexpected end of data
text = JSON.parse(jsonGet.responseText);
Relevant parts of the function:
函数的相关部分:
function populateList(){
//retrieves list from the server, adds it to the option box
if(toggle == 0){
var jsonGet = new XMLHttpRequest();
jsonGet.open("GET","./json/GetAllEvents.php",true);
jsonGet.onreadystatechange = function () {
text = JSON.parse(jsonGet.responseText); //ERROR HERE
//updating html with data received
};
jsonGet.send();
toggle = 1;
} else {}
};
The JSON returned looks like this (without the line breaks):
返回的 JSON 如下所示(没有换行符):
{"success":true,
"number_of_rows":2,
"data":[
{"id":"7","event_name":null,"day":3,"start_time":510,"end_time":617},
{"id":"8","event_name":null,"day":1,"start_time":510,"end_time":617}
]}
JSONLintsays that the above is valid. I guess I will take a look into whether XMLHttpRequest does anything strange. Firefox continues to function (even though firebug shows the error), IE9 stops at this point though.
JSONLint表示上述内容有效。我想我会研究一下 XMLHttpRequest 是否做了什么奇怪的事情。Firefox 继续运行(即使 firebug 显示错误),但此时 IE9 停止。
I'm pretty stumped. Any help is appreciated.
我很难过。任何帮助表示赞赏。
回答by bfavaretto
You have to check if jsonGet.readyState==4 && jsonGet.status==200
before parsing the response.
您必须jsonGet.readyState==4 && jsonGet.status==200
在解析响应之前检查是否。