我试图从每个循环的下拉框中根据我的选择从JSON文件获取有关年份的数据。我希望我的代码是这样的:点击下拉框中的值年份,然后一个表格显示文件中所有对象的值与所选的年份相同。
这是我的代码:
<!DOCTYPE html>
<html>
<body>
<form>Select a YEAR :
<select id="Selections">
<option value="year1">year1</option>
<option value="year2">year2</option>
</select>
</form>
<button type="button" onclick="run()">Try it</button>
<p id="result"> </p>
<script>
function run () {
var x = document.getElementById("Selections").value;
if (x == "year1") {
document.getElementById("result").innerHTML = "the first year";
$.getJSON("year1.json", function(json) {
$.each(json, function (i,item){
$('#tblinfo').append('<tr> <th>'+item.year+'</th>
<th>'+item.eposide+'</th></tr>');
})
});
} else if (x == "year2") {
document.getElementById("result").innerHTML = "the second year";
$.getJSON("year2.json", function (json) {
$.each(json, function (i,item){
$('#tblinfo').append('<tr> <th>'+item.year+'</th>
<th>'+item.eposide+'</th></tr>');
})
});
}
}
</script>
<table id="tblinfo" border=" 1px solid black" style="width:100%"></table>
</body>
</html>
我的JSON文件:
year1.json是:
[
{"year":"1995", "eposide":"1"},
{"year":"1995", "eposide":"2"},
{"year":"1995","eposide":"3"}
]
year2.json是:
[
{"year":"1994", "eposide":"1"},
{"year":"1994", "eposide":"2"},
{"year":"1994","eposide":"3"}
]
不知何故,我无法在表格中获得任何价值。
答案 0 :(得分:-1)
<!doctype html>
<html>
<body>
Select YEAR :
<select id="Selections" onchange="run()">
<option value="0">choose:</option>
<option value="1">year1</option>
<option value="2">year2</option>
</select>
<p id="result"></p>
<template id="temp">
<span class="year"></span>
<span class="episode"></span><br>
</template>
<script>
let url;
function run(){
let e=document.querySelector("#Selections");
let year=e.options[e.selectedIndex].value;
if(year==1)url="year1.json";
else if (year==2)url="year2.json";
getJson();
}
async function getJson() {
let temp=document.querySelector("#temp");
let container = document.querySelector("#result");
let jsonObjects = await fetch(url);
let items = await jsonObjects.json();
container.innerHTML="";
items.forEach(function(item) {
let clon = temp.cloneNode(true).content;
clon.querySelector(".year").textContent = item.year;
clon.querySelector(".episode").textContent = item.eposide;
container.appendChild(clon);
});
}
</script>
</body>
</html>