我有一个Java REST API,其中包含一些我正在使用JSon数据的JSOn数据。
我有两种方法来显示数据,以及何时添加新数据:
所以我在第一个bata中添加了一个EventListener来提交数据:
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);
addPerson(data);
};
request.send();
});
使用如下的addPerson方法:
const addPerson = (data) => {
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var age = document.getElementById("age").value;
var id = data[data.length-1].id +1;
const person = {fName, lName, age, id};
data.push(person);
console.log(person);
for(i = 0; i< data.length; i++){
console.log(data[i]);
}
}
问题是,每个GET请求都会生成新数据,所以我只想提取一次数据,然后将其保存在数组中,然后从那里添加新人员。
在将JSON数据转换为对象之后,我还有一种方法来显示它:
我像在调用此方法之前一样,将事件侦听器添加到了另一个按钮:
render HTML = (data) => {
let htmlString = "";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + " " + data[i].lName + " " + data[i].age + " " + data[i].id + "</p>"
}
root.insertAdjacentHTML('beforeend', htmlString);
}
答案 0 :(得分:1)
//bind click event on button to add person info
addPersonbtn.addEventListener('click', function() {
addPerson();
});
// fetch all person data from api (call this function when app load)
function getPersonList() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function(){
var data = JSON.parse(request.responseText);
renderHTML(data);
};
request.send();
}
function postPersonData(personInfo) {
// your api to add single persion info
// on success call getPersonList(), it will update the list
}
const addPerson = () => {
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var age = document.getElementById("age").value;
//var id = data[data.length-1].id +1; // handle it on db side, Primary key, auto generation
const person = {fName, lName, age};
postPersonData(person);
}
renderHTML = (data) => {
let htmlString = "";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + " " + data[i].lName + " " + data[i].age + " " + data[i].id + "</p>"
}
root.insertAdjacentHTML('beforeend', htmlString);
}
我为您制作了伪代码,希望它能对您有所帮助