gpt4 book ai didi

javascript - 如何从 json 中读取多组结果?

转载 作者:行者123 更新时间:2023-11-30 13:45:31 27 4
gpt4 key购买 nike

我正在使用以下代码获取包含员工信息的 JSON 结果,但有时可能会获取不止一组结果,我需要阅读所有结果。

function get_employee(employee_id) {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});


};

getJSON('https://company.com/index.php?employee_id=' + employee_id + '&format=json').then(function(data) {
$('#employee').val('');
if (data.employees.length > 0) {

var employee = data.employees.shift();
document.getElementById("date_1").textContent = employee.employees.DATE_1;
document.getElementById("date_2").textContent = employee.employees.DATE_2;
document.getElementById("date_3").textContent = employee.employees.DATE_3;

} else {
$('#myModal').modal('show');
}
}, function(status) { //error detection....
alert('Someting went wrong.');
});
}

有时我会得到这样的结果:

{ 
"employees":[
{
"employee":{
"EMPLOYEE_ID":"125678",
"DATE_1":"30-06-2018",
"DATE_2":"30-06-2017",
"DATE_3":"12-07-2021"
}
},
{
"employee":{
"EMPLOYEE_ID":"125678",
"DATE_1":"01-04-2021",
"DATE_2":"01-04-2021",
"DATE_3":"02-04-2022"
}
}
]
}

我需要存储所有涉及的日期。如何获得第二组结果?

最佳答案

js 对象的基本内容:

const myTable = document.querySelector('#my-table')
, data = { employees:
[ { employee: { EMPLOYEE_ID: "125678", DATE_1: "30-06-2018", DATE_2: "30-06-2017", DATE_3: "12-07-2021"} }
, { employee: { EMPLOYEE_ID: "125678", DATE_1: "01-04-2021", DATE_2: "01-04-2021", DATE_3: "02-04-2022"} }
] }
;
for ( let elm of data.employees )
{
let nRow = myTable.insertRow(-1)
, col = 0
;
nRow.insertCell(col++).textContent = elm.employee.DATE_1
nRow.insertCell(col++).textContent = elm.employee.DATE_2
nRow.insertCell(col++).textContent = elm.employee.DATE_3
};
let Rowhead = myTable.createTHead().insertRow(-1);
['DATE_1','DATE_2','DATE_3'].forEach((T,i)=>Rowhead.insertCell(i).textContent = T);
Table { border-collapse: collapse; margin: .7em; }
td { border: 1px solid grey; padding: 2px 10px; }
thead { background-color: turquoise;}
<table id="my-table"></table>

关于javascript - 如何从 json 中读取多组结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59418954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com