我有这样的对象。
{image: "img", images: "["1561971738beach-2179624_960_720.jpg","1561971738…"1561971738photo-1507525428034-b723cf961d3e.jpg"]", name: "aaa", surname: "bbb", text: "test", …}
image: "img"
images: "["1561971738beach-2179624_960_720.jpg","1561971738pexels-photo-457882.jpeg","1561971738photo-1507525428034-b723cf961d3e.jpg"]"
name: "aaa"
surname: "bbb"
text: "test"
user_id: 2
images字段包含每个帖子具有的图片的JSON。在打印帖子时如何将每个帖子的图像放入其中?
我的代码:
$.ajax({
url: '/loadPosts',
type: 'GET',
dataType: 'json',
data: {_token: "{{ csrf_token() }}"},
success: function(r){
r.forEach((post)=>{
var images = JSON.parse(post.images);
$('.posts-div').append(`
<div class="card mb-3">
<h5 class="card-header">
<img src="images/${post.image}" style="width: 35px; height: 35px;">
${post.name} ${post.surname}
</h5>
<div class="card-body">
<p class="card-text">${post.text}</p>
NEED TO PUT IMAGES HERE.
<div class="heart-div">
<img class="heart" src="http://www.clipartroo.com/images/96/black-heart-clipart-96717.png">
</div>
</div>
</div>
`);
})
}
})
答案 0 :(得分:0)
您反复遍历了post images数组,如下所示:
最后,将其附加append()。
$.ajax({
url: '/loadPosts',
type: 'GET',
dataType: 'json',
data: {_token: "{{ csrf_token() }}"},
success: function(r){
r.forEach((post)=>{
var string = `<div class="card mb-3">
<h5 class="card-header">
<img src="images/${post.image}" style="width: 35px; height: 35px;">
${post.name} ${post.surname}
</h5>
<div class="card-body">
<p class="card-text">${post.text}</p>`;
for(image in post.images){
var string = string + `<img src="images/${image}" style="width: 35px; height: 35px;">`;
}
var string = string + `<div class="heart-div">
<img class="heart" src="http://www.clipartroo.com/images/96/black-heart-clipart-96717.png">
</div>
</div>
</div>`;
$('.posts-div').append(string);
})
} })
这里是整个ajax调用,只是复制粘贴,我没有“编译”它,所以也许有一些语法错误,但是逻辑是完美无缺的,所以告诉我它是如何工作的。