简体   繁体   中英

How to map JSON Data from an API to a div

I've been working on an app that fetches data from an API and then neatly puts them into card div's. I've written the code for performing the request and getting all the data in JSON (image below), however I can't find a way to keep my code clean and manage the results.

What i want to do is create a div called card for each JSON object (there are 50 in the picture below) and then inside those divs i append span tags with the information.

Here's my current code

  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4) {
      results.style.opacity = 1
      let result = xhr.responseText
      result = JSON.parse(result)
      console.log(result)

Create the function and pass the JSON data to that function and then you need to iterate the loop for the key name results . Then access the each element by using the key name of the array's object. Below is the example code (css not included). More about object

<body>
    <div id="container">

    </div>
</body>

<script>

xhr.onreadystatechange = () => {
    if (xhr.readyState == 4) {
    results.style.opacity = 1
    let result = xhr.responseText
    result = JSON.parse(result)
    loadDiv(result);
    }
}



function loadDiv(data){
    for(var x of data.results){

        var div = `<div class="cols">
        <a href="${x.url}">${x.mal_id}</a>
        <img src="${x.url}"/>
        </div>
        `;
        document.getElementById("container").insertAdjacentHTML("beforeend",div);

    }

}

You can iterate the object and create divs and spans.

 // I expect your results in this variable. var result = { results: [{ One: 'div', Two: 'span' }] }; result.results.forEach(data => { var div = document.createElement('div'); div.id = 'block'; div.className = 'block'; var span = document.createElement('span'); span.className = 'block-2'; div.appendChild(span); document.getElementsByTagName('body')[0].appendChild(div); });
 .block { height: 50px; width: 50px; border: 1px solid red; }.block-2 { height: 20px; width: 20px; border: 1px solid blue; position: absolute; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM