【发布时间】:2022-09-23 09:21:59
【问题描述】:
我目前正在做学校作业。目标是使用 Django 和 JavaScript 制作一个简单的社交网络发布应用程序。 JavaScript 用于动态加载网页上的帖子并替换 HTML 部分。我正在关注 YouTube 课程 https://youtu.be/f1R_bykXHGE 来帮助我。尽管我已经按照教程进行了操作,但我收到以下未捕获的类型错误:无法在 XMLHttpRequest.xhr.onload ((index):63:28) 处读取未定义的属性(读取 \'length\')。
const postsElement = document.getElementById(\"posts\") // get an html element
// postsElement.innerHTML = \'Loading...\' // set new html in that element
// var el1 = \"<h1>Hi there 1</h1>\"
// var el2 = \"<h1>Hi there 2</h1>\"
// var el3 = \"<h1>Hi there 3</h1>\"
// postsElement.innerHTML = el1 + el2 + el3
const xhr = new XMLHttpRequest()
const method = \'GET\' // \"POST\"
const url = \"/posts\"
const responseType = \"json\"
xhr.responseType = responseType
xhr.open(method, url)
xhr.onload = function() {
const serverResponse = xhr.response
const listedItems = serverResponse.response // array
var finalPostStr = \"\"
var i;
for (i=0;i<listedItems.length;i++) {
console.log(i)
console.log(listedItems[i])
}
}
xhr.send()
</script>
-
您应该迭代
xhr.responseText,它始终是一个字符串,而不是一个数组。如果字符串是 JSON 格式,您可以使用JSON.parse将其解析为数组。
标签: javascript html json django