I have a problem in using loop since i didn’t know what kind of loop to use in this case (sorry i’m still learning jquery & js!). In the result page I have created card to separate each data from json, but i’m stuck on how to display the data inside each card.Here is the breakdown:
result example
code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>Display data json into cards</title>
</head>
<body>
<div class="container">
<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">
<div class="card-header"></div>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"></p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"</script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId; //this should be in div class = "card-header"
var typeId = item.id; //this should be in div class = "card-header"
var titleId = item.title; //this should be in h5 class = "card-title"
var bodyId = item.body; //this should be in p class = "card-text"
var html = '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
html += '<div class="card-header"></div>';
html += '<div class="card-body">';
html += '<h5 class="card-title"></h5>';
html += '<p class="card-text"></p>';
html += '</div>';
html += '</div>';
html += '</div>';
//use loop below here and inject to div.container
$(".container").html(html); //using .html() will display one card,use loop to display each card
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
</body>
</html>
Sorry for asking a bit much, and thank you for the help!
2
Answers
.each
the problem is you didn’t pass/concatenate the variables in your js/html[1] Using css,js
.append()
[2] If you want to use
.html()
you need to define thevar html
before theeach()
then let the.each
update thehtml +=
value then use the.html()
after the.each()
I still prefer the first solutionTry using the following solution:
To bind the variable inside the string use “
And see the following in the stackblitz demo:
https://stackblitz.com/edit/js-xfs15o?file=index.html