#javascript #html #json
#javascript #HTML #json
Вопрос:
Я пытаюсь создать html-страницу, содержащую таблицу стран, # случаев и # смертей, которая при загрузке страницы отображает все страны с тегом select для просмотра только данных по отдельным странам. У меня возникла проблема с выбором параметров, отличных от «Все страны», как будто я выбираю что-то еще, оно не возвращает их данные. Любая помощь будет оценена, и я заранее приношу извинения за мой грязный код
let countriesJSON = null // this will be loaded once in ajaxListAllCountries() and used in listAllStatsInCountry()
let totalCountries = []
async function ajaxListAllCountries() {
let url = `covidData.json` /* name of the JSON file */
try {
const response = await fetch(url, {
method: `POST`,
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
})
updateWebpage(await response.json())
} catch (error) {
console.log('Fetch failed: ', error)
}
/* use the fetched data to change the content of the webpage */
function updateWebpage(jsonData) {
let uniqueCountries = []
let countryCases = []
let countryDeaths = []
// save the list of countries to local memory
countriesJSON = JSON.parse(JSON.stringify(jsonData))
let countries = jsonData.records.map(country =>
({
Country: country.countriesAndTerritories,
Cases: country.cases,
Deaths: country.deaths
})
)
// get the list of unique countries
let countryNames = countries.map(country => country.Country)
uniqueCountries = Array.from(new Set(countryNames)).sort()
uniqueCountries.unshift("All Countries") // add "All Countries" to the front of the array
const sumCountryCases = (countries, name) => {
let total = 0
countries.forEach(cases => {
if (cases.Country === name) {
total = cases.Cases
}
})
return total
}
for (let i = 0; i < uniqueCountries.length; i ) {
countryCases[i] = sumCountryCases(countries, uniqueCountries[i])
}
const sumCountryDeaths = (countries, name) => {
let total = 0
countries.forEach(deaths => {
if (deaths.Country === name) {
total = deaths.Deaths
}
})
return total
}
for (let i = 0; i < uniqueCountries.length; i ) {
countryDeaths[i] = sumCountryDeaths(countries, uniqueCountries[i])
}
for (let i = 0; i < uniqueCountries.length; i ) {
totalCountries[i] = {
Country: uniqueCountries[i],
Cases: countryCases[i],
Deaths: countryDeaths[i]
}
}
console.log(totalCountries)
console.log(uniqueCountries)
let htmlString = `<select id="countries" onChange="listAllStatsInCountry(this.value)">`
uniqueCountries.map(country => {
if (country !== "") {
htmlString = `<option value = "${country}">${country}</option>`
}
})
htmlString = `</select>`
document.getElementById('countries').innerHTML = htmlString
// list all countries when the webpage opens
listAllStatsInCountry("All Countries")
}
}
function listAllStatsInCountry(country) {
let statsInCountry = null;
if (country === "All Countries") {
statsInCountry = totalCountries
} else if (country === "No Country") {
statsInCountry = totalCountries.filter(country => country.Country === "")
} else {
statsInCountry = totalCountries.filter(country => country.Country === country)
}
let htmlString = `<table id="countriesTable"><tr><th>Country</th><th>Cases</th><th>Deaths</th></tr>`
statsInCountry.map(country => {
if (country.Country !== "All Countries") {
htmlString = `<tr>
<td>${country.Country}</td>
<td>${country.Cases}</td>
<td>${country.Deaths}</td>
</tr>`
}
})
htmlString = `</table><br>${statsInCountry.length} records found.`
document.getElementById('allCountries').innerHTML = htmlString
}
<html>
<head>
<title>Global Covid-19 Statistics</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
</script>
</head>
<body onload="ajaxListAllCountries()">
<div id="countries"></div>
<div id="allCountries"></div>
</body>
</html>
РЕДАКТИРОВАТЬ — Добавлен небольшой фрагмент образца данных из файла json
{
"records": [{
"dateRep": "31/10/2020",
"day": "31",
"month": "10",
"year": "2020",
"cases": 157,
"deaths": 4,
"countriesAndTerritories": "Afghanistan",
"geoId": "AF",
"countryterritoryCode": "AFG",
"popData2019": 38041757,
"continentExp": "Asia",
"Cumulative_number_for_14_days_of_COVID-19_cases_per_100000": "3.55398937"
},
{
"dateRep": "17/05/2020",
"day": "17",
"month": "05",
"year": "2020",
"cases": 4,
"deaths": 0,
"countriesAndTerritories": "Estonia",
"geoId": "EE",
"countryterritoryCode": "EST",
"popData2019": 1324820,
"continentExp": "Europe",
"Cumulative_number_for_14_days_of_COVID-19_cases_per_100000": "5.35921861"
},
{
"dateRep": "16/01/2020",
"day": "16",
"month": "01",
"year": "2020",
"cases": 0,
"deaths": 0,
"countriesAndTerritories": "Estonia",
"geoId": "EE",
"countryterritoryCode": "EST",
"popData2019": 1324820,
"continentExp": "Europe",
"Cumulative_number_for_14_days_of_COVID-19_cases_per_100000": "0"
}
Комментарии:
1. Это » У меня проблема с выбором параметров, отличных от «Все страны» » вопрос о том, что чьи-то URL-адреса конечных точек API не работают? Разве вы не должны спросить поставщика услуг или прочитать их документацию?
2. @RandyCasburn не используя API, я загрузил данные с data.europa.eu/euodp/en/data/dataset/covid-19-coronavirus-data и использовать это как json-файл.
3. ОК. Пожалуйста, нам нужно просмотреть небольшую выборку данных из этого файла.
4. @RandyCasburn обновил сообщение с некоторыми примерами данных, не знаю, будет ли этого достаточно, поскольку данные имеют более 50 тыс. свойств, часть кода предназначена для удаления дублирующих стран и добавления их случаев и смертей к общему значению
Ответ №1:
Вам вообще не нужен POST
запрос, поскольку вы просто GET
вводите файл. В противном случае ваш код работает нормально, как показано здесь: http://plnkr.co/edit/sAUdQx7dUckGAOrC
Редактировать в ответ на комментарий OP:
Оба фильтра неверны в listAllStatsInCountry()
функции. В настоящее время фильтры массива записаны:
statsInCountry = totalCountries.filter(country => country.Country === country)
В обоих случаях использование переменной country
в качестве параметра функции со стрелкой затеняет переменную внешней области с тем же именем. Таким образом, фильтр никогда ничего не находит. Чтобы исправить это, измените имена параметров фильтров на что-то другое, подобное этому:
statsInCountry = totalCountries.filter(c => c.Country === country)
Это будет работать. Plunkr был обновлен.
Изменить:
const response = await fetch(url, {
method: `POST`,
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
})
Для:
const response = await fetch(url);`
Комментарии:
1. Как мне обновить его, чтобы при выборе страны отображались только принадлежащие ей данные?