gpt4 book ai didi

javascript - 使用ajax/javascript显示多个json数组

转载 作者:行者123 更新时间:2023-11-28 16:01:18 24 4
gpt4 key购买 nike

我在显示多个 JSON 数组时遇到一些问题,如果有人可以提供帮助,我会很感激。

JSON

{ 
"houseOne": [
{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}
],

"houseTwo": [
{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}
]

}

Javascript

<script type="text/javascript">
function ajaxRequest(url)
{
var request = new XMLHttpRequest();

// Work around for IE caching problem
if (url.indexOf('?') < 0) {
today = new Date();
url += '?' + today.getTime();
}

request.open("GET", url, false);
request.setRequestHeader("Cache-Control", "no-cache");
request.send();
return request.responseText;
}

var data = ajaxRequest("results.json");
var houses = JSON.parse(data);

function displayJson() {
var myDiv =document.getElementById("content");
for (house = 0; house < 3; house++) {
var home = houses.houseOne[house];
myDiv.innerHTML += houseDetails(home,house);

}
}


function houseDetails(home,houseNumber){


var myHTML = "<h1>House Mate "+ (houseNumber +1)+"</h1>";
myHTML += "<table>";
myHTML += "<tr><th>Name</th><th>Age</th><th>D.O.B</th></tr>";
myHTML += "<tr>";
myHTML += "<td>";
myHTML += home.name;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.age;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.dob;
myHTML += "</td>";
myHTML += "</table>";

return myHTML



}

</script>

基本上我可以让它将 houseOne 显示为表格,但我无法让它同时显示 houseOne 和 houseTwo,我希望这一点很清楚,我不太擅长网络开发。

问候,

院长

最佳答案

在您的 displayJson() 函数中,您仅引用 house.houseOne

var home = houses.houseOne[house];

这是更新版本(我也添加了 jQuery)http://jsfiddle.net/XzZUR/1/

JSON

var houses = {
"houseOne": [{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}],

"houseTwo": [{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}]
};

Javascript

function displayJson() {
var myDiv = $("#content");

$.each(houses, function(){
var house = this;
$(house).each(function(key){
myDiv.append(houseDetails(this,key));
})
});

}

关于javascript - 使用ajax/javascript显示多个json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16880809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com