javascript - 如何修复“未捕获的类型错误:无法读取未定义的属性“长度”
问题描述
目前正在为我的作品集做一个网站项目,最近我得到了一本 javascript 和 jquery 的书来帮助我学习这种新语言,因为我已经熟悉了 HTML 和 CSS+Sass。
我正在处理的项目涉及访问一个域内 JSON 文件,该文件包含一些我想使用 ajax 以 HTML 格式显示的简单数据,但唯一的问题是我收到此错误“未捕获的类型错误:无法读取属性”未定义的“长度”。
任何帮助,将不胜感激!
javascript / ajax
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var project;
for (var i = 0; i < responseObject.events.length; i++) {
//for loop
project = '<div class="display-item>';
project += '<div class="title">' + responseObject.events[i].name + '</div>';
project += '<div class="sourcelink">' + responseObject.events[i].source-code-link + '</div>';
project += '<div class="livelink">' + responseObject.evetns[i].live-link + '</div>';
project += '<div class="isPrivate>' + responseObject.events[i].isPrivate + '</div>';
project += '<div class="isLive">' + responseObject.events[i].isLive + '</div>';
project += '</div>';
}
//Update page with new content
document.getElementById('openSourceContent').innerHTML = project;
}
};
xhr.open('GET', '../js/data/htmlProjects.json', true); //Prepare request
xhr.send(null); //Send request
正在处理的json
{
"projects" : [
{
"name" : "Minimalist Template 1",
"source-code-link" : "https://github.com/CandyPheonix/html5-minimalist-template",
"live-link" : "https://candypheonix.github.io/html5-minimalist-template/",
"isPrivate" : "false",
"isLive" : "true"
},
{
"name" : "Minimalist Template 2",
"source-code-link" : "https://github.com/CandyPheonix/html5-minimalist-template-2",
"live-link" : "https://candypheonix.github.io/html5-minimalist-template-2/",
"isPrivate" : "false",
"isLive" : "true"
}
]
}
我的预期结果是让 ajax 读取 JSON 文件数据并将其解析为 HTML 就绪代码,以便它可以显示在浏览器上,但它给了我未定义错误的“长度”。
控制台中发生的错误: **Uncaught TypeError: Cannot read property 'length' of undefined at MLHttpRequest.xhr.onload (jsonDecompileToHTML.js:8)
xhr.onload@jsonDecompileToHTML.js:8
加载(异步)
(匿名)@ jsonDecompileToHTML.js:2**
附言。很抱歉没有使用 jQuery,我还在学习!
解决方案
首先,我想指出这是一个新手错误,因为只有一条随机评论告诉我 responseObject 不使用名为“events”的属性,我意识到这就是 JSON 的名称阵列应该去。
附言。我发现的另一件事是,你不能在分隔词中使用带有“-”的键,最好只使用“exampleExample”。
这只是表明,即使是直接的答案也无法帮助您解决问题,哈哈。
推荐阅读
- amazon-web-services - 如何防止 Terraform 用 CodeDeploy 替换 ECS 服务
- javascript - IF 语句中的 Javascript“NaN”
- firebase - Save way to create a Firestore document
- python - 按列表顺序替换值
- python - lxml etree cleanup_namespaces 返回 None 而不是清理的树
- c# - 多对多关系,桥接表 - 如何插入重复的主键?
- python-3.x - Tkinter:当用户不滚动时自动滚动到底部
- node.js - 获取 Azure Blob(图像)并 POST 到外部 API
- c# - 上传 BLOB 时出现此错误“Google.Apis.Requests.RequestError Not Found [404]”的解释是什么?
- python - 这两种形式的相对导入是否完全相同?