Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在这种AJAX情况下,如何在网页上输出所有这些JSON对象?_Javascript_Html_Json_Ajax - Fatal编程技术网

Javascript 在这种AJAX情况下,如何在网页上输出所有这些JSON对象?

Javascript 在这种AJAX情况下,如何在网页上输出所有这些JSON对象?,javascript,html,json,ajax,Javascript,Html,Json,Ajax,我希望能够通过一个按钮从网页上的JSON文件中输出所有这些对象及其内容。请不要告诉我使用console.log,我并不是想这么做,我实际上想在网页上输出这个,我不知道怎么做。忽略我试图从对象获取单个内容的部分。 JSON文件 { "name": "Adam", "age": 21, "interest": ["food", "relaxing"] }, { "name": "Bob", "age":

我希望能够通过一个按钮从网页上的JSON文件中输出所有这些对象及其内容。请不要告诉我使用console.log,我并不是想这么做,我实际上想在网页上输出这个,我不知道怎么做。忽略我试图从对象获取单个内容的部分。 JSON文件

{
        "name": "Adam",
        "age": 21,
        "interest": ["food", "relaxing"]
    },

    {
        "name": "Bob",
        "age": 22,
        "interest": ["working out", "sleeping"]
    },

    {
        "name": "Cane",
        "age": 23,
        "interest": ["football", "vide games"]
    }
AJAX文件

<!DOCTYPE html>
<html>
<body>

<div id="demo">

<button type="button" onclick="x()">Change Content</button>
</div>

<script>
function x() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var employees = JSON.parse(xhr.responseText);
document.getElementById("demo").innerHTML =
employees.name;
}
};
xhr.open("GET", "json_example.json", true);
xhr.send();
}
</script>

</body>
</html>

更改内容
函数x(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
var employees=JSON.parse(xhr.responseText);
document.getElementById(“demo”).innerHTML=
雇员姓名;
}
};
open(“GET”,“json\u example.json”,true);
xhr.send();
}

使用
pre
标签

HTML

<pre id="jsonText"></pre>

请参阅stringify文档

,了解无效结构的初学者。缺少外部数组引号
[]
。使用在线json验证器来验证您的json。这不是重复的,这是基于情况的,甚至不接近重复。
document.getElementById("jsonText").innerHTML = JSON.stringify(employees, null, 2);