向数组添加元素时出现 Javascript 未定义错误
2018-09-22
94
我有一个 Json 数组,我正在将其解析为 javascript 对象数组。
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function() {
var data = JSON.parse(request.responseText);
// renderhtml(data);
addPerson(data);
};
request.send();
});
我创建了一个 addPerson 函数来将用户定义的对象添加到列表中。
addPerson = (data) => {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var age = document.getElementById("age");
var id = data.pop()+1;
const person = {fName, lName, age, id};
data.add(person);
}
调用该函数时,我收到“addPerson 未定义”错误。这是为什么?
这是我的整个文件:
var btn = document.getElementById("btn");
var root = document.getElementById("root");
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function(){
var data = JSON.parse(request.responseText);
//renderhtml(data);
addPerson(data);
};
request.send();
});
renderhtml = (data) => {
let htmlString = " ";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + data[i].lName + "</p>"
}
addPerson = (data) => {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var age = document.getElementById("age");
var id = data.pop()+1;
const person = {fName, lName, age, id};
data.push(person);
}
root.insertAdjacentHTML('beforeend', htmlString);
}
2个回答
这是因为你没有正确关闭你的
renderHTML
函数,应该是这样的:
renderhtml = (data) => {
let htmlString = " ";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + data[i].lName + "</p>"
}
} // <-- Add closing bracket to renderHTML function here
addPerson = (data) => {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var age = document.getElementById("age");
var id = data.pop()+1;
const person = {fName, lName, age, id};
data.push(person);
}
Nick Parsons
2018-09-22
尝试将整个 addPerson 函数移到 renderhtml 函数之外,很可能是因为 addPerson 函数位于 renderhtml 函数内部
Rio Hilmy
2018-09-22