Kody R. February 2016

JSON Parse error: Unexpected identifier

I pulled this directly from W3 schools website on their JSON tutorial, but I keep getting an error message JSON Parse error: Unexpected identifier "var" and it's pointing to the line:

"var myArr = JSON.parse(xmlhttp.responseText);

<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myserveraddress/myTutorials.txt";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}

</script>
</body>
</html>

EDIT: As requested here is the link to the W3 page that has the tutorial http://www.w3schools.com/json/json_http.asp and here is the link that has the demohttp://www.w3schools.com/json/tryit.asp?filename=tryjson_http

Also here is what my myTutorials.txt file looks like

var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]

Answers


Quentin February 2016

Also here is what my myTutorials.txt file looks like

That's wrong.

You've put the content of the box marked myArray in that file.

The contents of the box marked myTutorials.txt looks like this:

[
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]

Post Status

Asked in February 2016
Viewed 1,048 times
Voted 9
Answered 1 times

Search




Leave an answer