jqueryjsonapi

I need to show json file comments by ID on my blog


I dont know how to call the JSON file so it will appear in the blog, I tried this method but it wont work. I think I need to use the each loop, but the only thing I get is error.

$.ajax({ type: "GET", url: "https://jsonplaceholder.typicode.com/comments", dataType: 'json', success: function (comment) {
    console.log(comment);
    commentsOn();
  }
});
 
function commentsOn(comments) {
  $("#comm").append(
    "<div class='card my-3'>postId:" + comments.postId +
    "<h6 class='caard-header'>ID:" + comments.id + "</div>" +
    "<div class='card-body'>Name:" + comments.name + "</div>" +
    "<p class='email'>Email:" + comments.email + "</p>" +
    "<textarea class='form-control comment-text'>Body:" + comments.body + "</textarea>" + "</div>"

  );
}


Solution

  • You can use $.getJSON() to get the data and the use .forEach() to add the data to the DOM. Try this

    $.getJSON('https://jsonplaceholder.typicode.com/comments', function (data) {
        data.forEach(item => {
            $("#comm").append(
                `<div class="card my-3">
                    postId: ${item.postId}
                    <h6 class="caard-header">ID: ${item.id}</div>
                    <div class="card-body">Name: ${item.name}</div>
                    <p class="email">Email: ${item.email}</p>
                    <textarea class="form-control comment-text">Body: ${item.body}</textarea>
                </div>`
            );
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="comm"></div>