- Suppose you have a site folder with content:
- index.html
- cities.json {"cities": ["newYork", "london"]}
- newYork.json {"name": "New York", "population": 999, "area": 232 }
- london.json {"name": "London", "population": 999, "area": 232 }
- ...
You have to find an application server to serve the folder on some port:
Example: https://www.npmjs.com/package/light-server
Command: light-server -s . -p 8000
Browser: http://localhost:8000 will render index.html
You can use also fetch to send HTTP requests and receive responses.
<html>
<body>
<div id="data"></div>
<script>
function render(city, data) {
let name = data.name;
let population = data.population;
let element = document.createElement("div");
element.innerHTML = city + "=> name:" + name + ", population: " + population
document.getElementById("data").append(element);
}
fetch("/cities.json").then(response => {
response.json().then(json => {
let cities = json.cities;
cities.forEach(city => {
fetch("/" + city + ".json").then(cityResponse => {
cityResponse.json().then(cityJson => {
render(city, cityJson)
})
})
})
})
})
</script>
</body>
</html>
<html>
<body>
<div id="data"></div>
<script>
function render(city, data) {
let name = data.name;
let population = data.population;
let element = document.createElement("div");
element.innerHTML = city + "=> name:" + name + ", population: " + population
document.getElementById("data").append(element);
}
let citiesRequest = new XMLHttpRequest();
citiesRequest.onload = function () {
let json = JSON.parse(this.responseText);
let cities = json.cities;
cities.forEach(city => {
let cityRequest = new XMLHttpRequest();
cityRequest.onload = function () {
let cityJson = JSON.parse(this.responseText);
render(city, cityJson);
}
cityRequest.open("GET", "/" + city + ".json", true);
cityRequest.send();
})
}
citiesRequest.open("GET", "/cities.json", true);
citiesRequest.send();
</script>
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…