Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ajax - Javascript - JSON.parse: unexpected end of data - Error when using valid JSON. What am I doing wrong?

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);

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):

{"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 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.

I'm pretty stumped. Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...