如何在AJAX中修复此JSON for循环?

时间:2017-08-07 23:26:44

标签: javascript html ajax

每当我按下按钮时按钮都不会消失,但它仍然会输出我喜欢的JSON文件中的内容,但是当我不断按下按钮时。相同的内容在页面上生成。所以我只想让按钮在我按下时消失,我希望JSON内容只显示一次。

Photo of the problem

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 id="bg" 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);
for(var i=0;i<employees.length;i++){
    employee = employees[i];
    document.getElementById("demo").innerHTML += "<br>" + employee.name;
}
}
};
xhr.open("GET", "json_example_2.json", true);
xhr.send();
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

要摆脱按钮,只需在上面添加以下行:

document.getElementById("demo").innerHTML = ""; // <- this line
var employees = ...;

这将在添加员工姓名之前清除innerHTML

如果你不想完全摆脱按钮,你也可以隐藏它:

document.getElementById("bg").style.display = 'none';