我正在使用https://disease.sh/v3/covid-19/jhucsse 上的 JSON API 。它將資料存盤為 JSON 物件串列。我正在制作一個小型網站,允許用戶滾動串列,選擇他們的國家和省,并查看該國家/省的資料。我為此使用了 JQuery,這是我目前的代碼:
const apiLink = "https://disease.sh/v3/covid-19/jhucsse"
jQuery(document).ready(function() {
jQuery("#SubmitButton").click(function() {
country_value = $('#country_picker').val() //Gets the value of the country_value select list in index.html
$.get(apiLink, function(data,status){
console.log(data[0]) // Placeholder code that prints the first JSON object in the list to the console
// Other code here
})
document.getElementById('output').innerHTML = TestHTML; // Fills the 'output' div element with the output of the program
});
});
我將如何解決這個問題?
uj5u.com熱心網友回復:
- 你不需要jQuery。您可以使用Fetch API
- 以JSON格式獲取資料
- 由于 JSON 資料是一個陣列,因此使用原型.forEach()或.reduce ()方法來提取每個國家/地區的資料
- 使用.addEventListener ()將
"input"事件附加到您的#search輸入元素 - 使用 String .includes ()方法檢查是否有任何行具有搜索值,如果值不匹配,則將
hidden屬性設定為該 TR 元素
下面是一個例子:
const EL = (sel, el) => (el || document).querySelector(sel);
const ELS = (sel, el) => (el || document).querySelectorAll(sel);
const EL_search = EL("#search");
const EL_table = EL("#table");
const EL_tbody = EL("tbody", EL_table);
let ELS_tr;
const apiLink = "https://disease.sh/v3/covid-19/jhucsse";
const row = (item) => `<tr>
<td>${item.country}</td>
<td>${item.province || ""}</td>
<td>${item.county || ""}</td>
<td>${item.stats.confirmed || "-"}</td>
<td>${item.stats.deaths || "-"}</td>
<td>${item.stats.recovered || "-"}</td>
</tr>`;
const build = (data) => {
EL_tbody.innerHTML = data.reduce((html, item) => html = row(item), "");
ELS_tr = ELS("tr", EL_tbody);
EL_search.addEventListener("input", search);
};
const search = () => {
const value = EL_search.value.trim().toLowerCase();
ELS_tr.forEach(EL_tr => {
const content = EL_tr.textContent.toLowerCase();
const match = content.includes(value);
EL_tr.hidden = value && !match;
});
};
fetch(apiLink).then(res => res.json()).then(build);
.sticky-thead {
position: relative;
max-height: 140px;
overflow-y: auto;
}
.sticky-thead table {
width: 100%;
border-spacing: 0;
border-collapse: separate;
}
.sticky-thead td,
.sticky-thead th {
text-align: left;
padding: 4px;
}
.sticky-thead thead th {
position: sticky;
top: 0;
background: #fff;
}
<input id="search" type="search" placeholder="Search" autocomplete="off">
<div class="sticky-thead">
<table id="table">
<thead>
<tr>
<th>Country</th>
<th>Province</th>
<th>County</th>
<th>Confirmed</th>
<th>Deaths</th>
<th>Recovered</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
uj5u.com熱心網友回復:
如果要填充串列,只需執行 for 回圈?data只是具有屬性的物件陣列。
for (let i = 0; i < data.length; i ) {
data[i].country // access the country
data[i].stats.deaths //access the deaths
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400889.html
標籤:javascript 查询 json 列表 接口
上一篇:快遞回復范圍
下一篇:如何決議嵌套的JSON物件?
