Home > database >  How to render a list using JavaScript
How to render a list using JavaScript

Time:10-28

Need help. I have a json file locally and I want to render a list. So that in the future I can add data to the json file and it will automatically appear on the page.

[
 {
   country: "England",
   cities: [
    {
      wikiLink: "https://en.wikipedia.org/wiki/London",
      citiesName: "London",
      citiesDescription: "is the capital and largest city of England and the United Kingdom, with a population of just under 9 million",
    },
    {
      wikiLink: "https://en.wikipedia.org/wiki/Liverpool",
      citiesName: "Liverpool",
      citiesDescription: "Is a city and metropolitan borough in Merseyside",
    },
   ]
 },
 {
   country: "Island",
   cities: [
    {
      wikiLink: "https://en.wikipedia.org/wiki/Reykjavík",
      citiesName: "Reykjavík",
      citiesDescription: "It is located in southwestern Iceland, on the southern shore of Faxaflói bay.",
    },
   ]
 },
]`

I want to get the following code after rendering

<div >
 <div >
  <h2 >England</h2>
  <ul >
      <li >
          <a  href="https://en.wikipedia.org/wiki/London" target="_blank">
             <span >London</span>
             - is the capital and largest city of England and the United Kingdom, with a    population of just under 9 million
             </a>
      </li>
      <li >
         <a  href="https://en.wikipedia.org/wiki/Liverpool" target="_blank">
              <span >Liverpool</span>
              - Is a city and metropolitan borough in Merseyside
         </a>
       </li>
  </ul>
 </div>
 <div >
   <h2 >Island</h2>
   <ul >
       <li >
         <a  href="https://en.wikipedia.org/wiki/Reykjavik" target="_blank">
            <span >Reykjavík</span>
               - It is located in southwestern Iceland, on the southern shore of Faxaflói bay.
         </a>
       </li>
    </ul>
 </div>
</div>`

This is roughly what I want to get

CodePudding user response:

You can use AJAX to fetch data from your JSON file and post it in your HTML Code, Ajax it's will give you the possibility to post, delete, update and get the data from your JSON file.

CodePudding user response:

The problem is, you can only use HTML and Javascript to render an existing file: you can't use them to change the file ... or at least not directly. Instead, you have use AJAX (AKA fetch) to send a request to a server, and then that server can change it.

You will need to learn a lot to be able to build such a server yourself, but luckily there is already an NPM package that does what you want. It starts a server, and then your front-end (ie. your HTML/JS) can use fetch to tell it about changes to your data, and it will save those changes in a JSON file on your computer.

Check out: https://www.npmjs.com/package/json-server

  • Related