Answer the question
In order to leave comments, you need to log in
How to add values from json to identical divs?
In general, there is code for adding values from json to div blocks:
$(document).ready(function(){
$.ajax({
url: 'ajax/prop',
dataType: 'html',
success:function(data){
var jsonStr = JSON.parse(data);
const container= document.getElementById('prop');
jsonStr.forEach(function(item) {
const itemDiv = document.createElement('button');
itemDiv.classList.add('btn');
itemDiv.id = item.id;
let innerHtml = '<dl>';
Object.keys(item).forEach(function(key) {
innerHtml += `
<dd>${item[key]}<dd>
`;
});
innerHtml += '</dl>';
itemDiv.innerHTML = innerHtml;
container.appendChild(itemDiv);
});
}
});
{"id":"1","time":"2 минуты"},{"id":"2","button":"Купить"},{"id":"3","back":"Вернуть"},{"id":"4","time":"1 минута"}
Answer the question
In order to leave comments, you need to log in
"If the names are wrong, everything is wrong" (c)
In the code for half of the variables, the name does not match the content. Accordingly, it is not clear what you mean by "first div": container or itemDiv (which is actually a button, not a div)?
Show with your hands the assembled HTML that you want to get as a result of the script, if you submit the given json as input.
var let const
document.getElementById and Jquery...
as far as I can see you don't understand what you are writing at all.
How it should work there is also not clear (it’s better to type everything on jsfiddle.net with json data, and show how it works, and what are the expectations), but the source code should look something like this:
$.ajax({
url: 'ajax/prop',
dataType: 'html',
success: function (data) {
let $container = $('#prop');
JSON.parse(data).forEach(item => {
let html = '<dl>';
Object.keys(item).forEach(key => html += `<dd>${item[key]}<dd>`);
html += '</dl>';
$container.append(`<button class="btn" id="${item.id}">${html}</button>`);
});
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question