简体   繁体   中英

How to dynamically populate a div from a JSON response

I'm trying to build a search platform. On the search results page, I already have three static divs containing the same code to display some contents.

Something like;

 <div id="result" class="card"> <img src="hello.png" class="card_img" alt="result image"> <h4>OFFLINE</h4> <p>Yes!!</p> </div> <div id="result" class="card"> <img src="hello.png" class="card_img" alt="result image"> <h4>OFFLINE</h4> <p>Yes!!</p> </div> <div id="result" class="card"> <img src="hello.png" class="card_img" alt="result image"> <h4>OFFLINE</h4> <p>Yes!!</p> </div> 

How do I loop the contents in this div to become dynamic so once a user hits a button;

 <button id="search" class="btn" value="Search"> 

The contents in this div loops, so I don't have to keep adding static divs. How do I make it dynamic with JavaScript?


EDIT

I am now wondering how to populate a div with children matching the contents of the JSON response below? Like a dynamically loaded list:

[{
    "name": "Malkov Chicken",
    "location": "New york",
    "meals": 5,
    "close_time": 1567289876354
},
{
    "name": "Delicious Chops",
    "location": "San francisco",
    "meals": 15,
    "close_time": 1567289876354
},
{
    "name": "Banana cultshop",
    "location": "New york",
    "meals": 8,
    "close_time": 1567289876354
}]

The div should pass the data from the JSON list, but the div should be looped according to the number of response from the JSON. So if the JSON responds with 5 objects, the divs should be 5.

If you want to add same HTML element with button click. Please note, you have to use class instead of id as id must be unique in a document.

You can try the following way:

 var template = `<div class="result" class="card"> <img src="hello.png" class="card_img" alt="result image"> <h4>OFFLINE</h4> <p>Yes!!</p> </div>`; var occurences = 3; document.getElementById('search').addEventListener('click', function(){ var strHTML = ''; for(var i=0; i<occurences; i++){ strHTML += template; } document.getElementById('container').insertAdjacentHTML('beforeend', strHTML); }); 
 <div id="container"></div> <button id="search" class="btn" value="Search">Create</button> 

Update:

 var listArr = [{ "name": "Malkov Chicken", "location": "New york", "meals": 5, "close_time": 1567289876354 },{ "name": "Delicious Chops", "location": "San francisco", "meals": 15, "close_time": 1567289876354 },{ "name": "Banana cultshop", "location": "New york", "meals": 8, "close_time": 1567289876354 }]; document.getElementById('search').addEventListener('click', function(){ var strHTML = ''; listArr.forEach(function(item){ strHTML += `<div class="Results-item"> <h4 class="Results-itemName">${item.name}</h4> <p class="Results-itemLocation"><b>${item.location}</b></p> <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p> </div>`; }) document.getElementById('container').insertAdjacentHTML('beforeend', strHTML); }); 
 <div id="container"></div> <button id="search" class="btn" value="Search">Create</button> 

Given a JSON Array of Objects, you could:

  • Create a string literal Template
  • .map() your JSON data into a templater TPL_Results function
  • Join the mapped result and insert into DOM

 const JSON = [{ "name": "Malkov Chicken", "location": "New york", "meals": 5, "close_time": '23:30' },{ "name": "Delicious Chops", "location": "San francisco", "meals": 15, "close_time": '22:00' },{ "name": "Banana cultshop", "location": "New york", "meals": 8, "close_time": '23:00' }]; const TPL_Results = item => `<div class="Results-item"> <h3 class="Results-itemName">${item.name}</h3> <p class="Results-itemLocation"><b>${item.location}</b></p> <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p> </div>`; document.querySelector("#results") .innerHTML = JSON.map(item => TPL_Results(item)).join(''); 
 <div class="Results" id="results"></div> 

If you wish to append multiple cards of the same content you can create a general template for one card in javascript, and append multiple of these cards to a container div.

If you wish to append multiple divs of the same content on button click, generate the string outside of the click event using a for loop, and then append the generated string.

Here I named the container div .content . Also, note, that each element should have a unique id, and so id's shouldn't be repeated.

See working example below:

 let card = `<div class="card"> <img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" class="card_img" alt="result image"> <h4>OFFLINE</h4> <p>Yes!!</p> </div>`; let amount = 10; // amount of cards to add on button click let toAppend = ''; for(let i = 0; i < amount; i++) { toAppend += card; } $("#search").click(function() { $('.content').empty().append(toAppend); }); 
 img { height: 150px; width: 150px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"></div> <button id="search" class="btn" value="Search">Click me</button> 

As per your edited question:

You can loop through your array of data using .reduce and construct a string of separate divs using template literals and destruction . After that, you can append this constructed div to your body or a div (here I have appended it to a div with the class content )

 let data = [{ "name": "Malkov Chicken", "location": "New york", "meals": 5, "close_time": 1567289876354 }, { "name": "Delicious Chops", "location": "San francisco", "meals": 15, "close_time": 1567289876354 }, { "name": "Banana cultshop", "location": "New york", "meals": 8, "close_time": 1567289876354 } ]; let html = data.reduce((acc, {name,location, meals, close_time: close}) => acc += ` <div class='item'> <p>${name}</p> <p>${location}</p> <p>${meals}</p> <p>${close}</p> </div>` , ``); $('.content').append(html); 
 .item { border: 1px solid black; margin: 10px 0; } p { margin: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"></div> 

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