javascript - JSON解析错误: Unexpected identifier

标签 javascript json

我直接从 W3 学校网站上的 JSON 教程中提取了此内容,但我不断收到错误消息 JSON 解析错误:意外的标识符“var” 并且它指向以下行:

“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>

编辑:根据要求,这里是包含教程 http://www.w3schools.com/json/json_http.asp 的 W3 页面的链接这是包含演示的链接http://www.w3schools.com/json/tryit.asp?filename=tryjson_http

这也是我的 myTutorials.txt 文件的样子

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

最佳答案

Also here is what my myTutorials.txt file looks like

这是错误的。

您已将标记为 myArray 的框的内容放入该文件中。

标记为myTutorials.txt的框中的内容如下所示:

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

关于javascript - JSON解析错误: Unexpected identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35277433/

相关文章:

javascript - HTML5 Canvas 使黑色透明

javascript - 如何从对象中获取数组的数量

java - 将多行字符串从 JsonNode 序列化为 YAML 字符串会添加双引号和 "\n"

json - 操纵mongodb的bson.D输出格式

json - 使用Chrome的开发工具调试JSON

c# - 如何在数据对象中收集数据集?

javascript - Magento 时事通讯成功消息弹出

javascript - 在 Firefox 中检测关闭窗口事件

javascript - 在 Javascript 中初始化多个变量的优雅方法

ruby-on-rails - 在 html 属性中发布数据时引用造成严重破坏