【问题标题】:javascript for loop error uncaught type error on .length.length 上的循环错误未捕获类型错误的 javascript
【发布时间】: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


【解决方案1】:

由于该属性未定义,您可能在views.py 文件中拼错了“response”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多