英文:
I need to show json file comments by ID on my blog
问题
我不知道如何调用JSON文件,以便它会出现在博客中,我尝试了这种方法,但它不起作用。我认为我需要使用each循环,但我得到的唯一的东西是错误。
$.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='card-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>"
);
}
希望这对你有帮助。
英文:
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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$.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>"
);
}
<!-- end snippet -->
答案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="card-header">ID: ${item.id}</h6>
<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>
英文:
You can use $.getJSON()
to get the data and the use .forEach()
to add the data to the DOM. Try this
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$.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>`
);
});
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="comm"></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论