使用Javascript - JSON.parse:数据意外结束 - 错误使用有效的JSON时。我究竟做错了什么? [英] Javascript - JSON.parse: unexpected end of data - Error when using valid JSON. What am I doing wrong?

查看:383
本文介绍了使用Javascript - JSON.parse:数据意外结束 - 错误使用有效的JSON时。我究竟做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我发现关于JQuery的类似的问题中,你并不需要解析。由于我使用了AJAX XMLHtt prequest,从我的理解,解析是必要的。该错误是给就行了:

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:

text = JSON.parse(jsonGet.responseText);

错误:

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 {}

};

在JSON返回看起来像这样(不换行):

The JSON returned looks like this (without the line breaks):

{"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}
]}

JSONLint 的说,上述是有效的。我想我会看看到XMLHtt prequest无论做什么奇怪的。火狐继续发挥作用(尽管萤火显示错误),IE9将停止在这一点上,虽然。

JSONLint says 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.

我是pretty的难住了。任何帮助是AP preciated。

I'm pretty stumped. Any help is appreciated.

推荐答案

您必须检查 jsonGet.readyState == 4安培;&安培; jsonGet.status == 200 前解析响应。

You have to check if jsonGet.readyState==4 && jsonGet.status==200 before parsing the response.

这篇关于使用Javascript - JSON.parse:数据意外结束 - 错误使用有效的JSON时。我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆