我对JS和jquery很新,你可以看到我的问题。但是,我试图在我的HTML页面中加载一些简单的JSON日期。我已经用一些项目做了几次但是这个显示了多个数据,其中一些是未定义的。
JSON DATA:
{"employment": [
{
"date": "June 16, 2014 - Present"
},
{
"company": "SAP/Concur Technologies Inc."
}
]}
结果:
June 16, 2014 - Present
undefined
undefined
SAP/Concur Technologies Inc.
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
还请告知我正在使用bootstrap。我不确定这是否会影响我的jquery。我试过控制台记录它并显示我的正确数据但由于某种原因,HTML显示了很多未定义的。我尝试检查调试器,但我似乎无法找到未定义的原因。
$.getJSON("data/data.json", (data)=>{
loadEmploymentData(data.employment);
console.log(data.employment);
});
function loadEmploymentData(employmentArray){
employmentArray.forEach((employment)=>{
$("#employment").append(`<ul><li>${employment.date}</li>
<li>${employment.company}</li></ul>`);
});
};
我非常感谢你的帮助。
答案 0 :(得分:0)
将结构更改为一个对象,其中包含每个就业职位的多个属性
var data = {
"employment": [{
"date": "June 16, 2014 - Present",
"company": "SAP/Concur Technologies Inc."
},
{
"date": "Jan 16, 1999 - Aug 7, 2012",
"company": "Some Co."
}
]
}
// no changes were made to this function
function loadEmploymentData(employmentArray) {
employmentArray.forEach((employment) => {
$("#employment").append(`<ul><li>${employment.date}</li>
<li>${employment.company}</li></ul>`);
});
};
// call function since not doing ajax in this demo
loadEmploymentData(data.employment)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="employment"></div>
&#13;
答案 1 :(得分:0)
这是您格式化JSON的方式。您有一个具有不同属性的对象列表,并且您尝试显示每个对象中的所有属性,因此您可以尝试在每次迭代中未定义
{"employment": [
{
"date": "June 16, 2014 - Present",
"company": "SAP/Concur Technologies Inc."
},
{
"date": "JuLy 14, 2014 - Freez",
"company": "team/rock Technologies Inc."
}
]}