ajax中itemtexts,javascript - Only the last item has the text in an ajax call - Stack Overflow

I'm having a hard time solving this problem.

Here's the code:

const postBox = document.querySelector('#posts')

const getUser = function(id, val) {

$.ajax({

type: 'GET',

url: `/api/user/${id}`,

success: function(response) {

val.innerHTML = `Posted by: ${response.username}`

},

error: function(error) {

console.log(error)

}

})

}

const getPosts = () => {

$.ajax({

type: 'GET',

url: '/api/posts/',

success: function(response) {

console.log(response)

response.forEach(el => {

postBox.innerHTML += `

${el.title}

${el.body}

${el.date}

`

const authorBox = document.querySelector(`#author${el.id}`)

console.log(authorBox)

getUser(el.author, authorBox)

})

},

error: function(error) {

console.log('error')

},

})

}

getPosts()

Only the last item has the "Posted by author"

I can't seem to figure out why only the last item has it. Even when I inspect it, it has the "Posted by author" inner html and inner text but it's not showing it.

here's the output:

Test 1

Test 1

2021-07-12

Test 2

Test 2

2021-07-12

Test 3

Test 3

2021-07-12

Test 4

Test 4

2021-07-12

Posted by: kyrios

How do I make sure that all of the authorBox has their inner html changed?

(edit)

This is the response from /api/posts/

Array(4) [ {…}, {…}, {…}, {…} ]

0: Object { id: 1, title: "Test 1", date: "2021-07-12", … }

1: Object { id: 2, title: "Test 2", date: "2021-07-12", … }

2: Object { id: 3, title: "Test 3", date: "2021-07-12", … }

3: Object { id: 4, title: "Test 4", date: "2021-07-12", … }

length: 4

each object is

author: 1

​​

body: "Test 1"

​​

category: 1

​​

date: "2021-07-12"

​​

id: 1

​​

image: null

​​

title: "Test 1"

I'm using the django rest framework generics ListViewApi.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值