如何解决这个JSON循环在AJAX? [英] How to fix this JSON for loop in AJAX?
本文介绍了如何解决这个JSON循环在AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JSON文件 $ b
[
{
name:Adam,
age:21,
interest:[food,relaxing]
},
name:Bob,
age:22,
interest:[work out,sleeping] $ b $ b,
name:Cane,
年龄:23,
兴趣:[足球,视频游戏]
}
]
AJAX文件
<!DOCTYPE html>
< html>
< body>
< div id =demo>
< button id =bgtype =buttononclick =x()>更改内容< / button>
< / div>
< script>
函数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>
解决方案
:
document.getElementById(demo)。innerHTML =; //< - 这一行
var employees = ...;
这将清除 innerHTML
,然后添加员工姓名。
如果你不想完全摆脱按钮,你也可以隐藏它:
document.getElementById(bg)。style.display ='none';
Every time when I press the button the button doesn't disappear but it still outputs the contents from the JSON file I love that but when I keep pushing the button more and more. The same contents keeps generating on the page. So I just want the button to disappear when I press it and I want the JSON contents to show one time only.
JSON File
[
{
"name": "Adam",
"age": 21,
"interest": ["food", "relaxing"]
},
{
"name": "Bob",
"age": 22,
"interest": ["working out", "sleeping"]
},
{
"name": "Cane",
"age": 23,
"interest": ["football", "vide games"]
}
]
The AJAX File
<!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>
解决方案
To get rid of the button just add this line above:
document.getElementById("demo").innerHTML = ""; // <- this line
var employees = ...;
This will clear the innerHTML
before adding the employee names.
If you don't want to get rid of the button entirely, you can also hide it:
document.getElementById("bg").style.display = 'none';
这篇关于如何解决这个JSON循环在AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文