我需要在我的博客上通过ID显示JSON文件评论

问题描述 投票:0回答:1
我不知道如何调用JSON文件,因此它将出现在博客中,我尝试了此方法,但它行不通。我认为我需要使用每个循环,但是我唯一得到的就是错误。

$.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>" ); }

jquery json
1个回答
1
投票

$.getJSON()

获取数据和使用
.forEach()
将数据添加到DOM中。尝试这个

$.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>

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.