无法访问已在javascript上声明的对象
我试图使用jquery的$.get方法在服务器上获取一些值,并将结果存储在一个对象中 我所做的是在循环中运行我的函数:无法访问已在javascript上声明的对象,javascript,jquery,Javascript,Jquery,我试图使用jquery的$.get方法在服务器上获取一些值,并将结果存储在一个对象中 我所做的是在循环中运行我的函数: function renderTabelScheduledEmploye(employees) { $('#containerDataStaff').empty(); let record = ''; let count = 1; if (employees.length > 0) { $.each(employees, function(key
function renderTabelScheduledEmploye(employees) {
$('#containerDataStaff').empty();
let record = '';
let count = 1;
if (employees.length > 0) {
$.each(employees, function(key, value) {
getFromServerScheduleCount(employees[key].schedule_employee_id);
console.log(scheduleCountData);
record += '<tr>';
record += '<td>' + count + '</td>';
record += '<td>( ' + employees[key].emp_kode + ') - ' + employees[key].emp_full_name + '</td>';
record += '<td>' + scheduleCountData[0].work + '</td>';
record += '<td>' + scheduleCountData[0].offDay + '</td>';
record += '<td>' + scheduleCountData[0].leave + '</td>';
record += '<td>' + scheduleCountData[0].shiftCount + '</td>';
record += '<td><a href="#" data-id="' + employees[key].schedule_employee_id + '" class="btnSettingShift">Set Shift</a></td>';
record += '</tr>';
count++;
});
}
$('#containerDataStaff').append(record);
}
我可以在控制台中看到对象已填充了数据
[object success to fill][1]
但是当我试图在这样的代码中访问
scheduleCountData[0]
scheduleCountData.new
并将结果记录到控制台,它显示undefined
这让我有点沮丧。我希望有人能帮助我。感谢社区
编辑:
对不起,我错过了
我试着用这样的代码调用那个对象
scheduleCountData[0]
scheduleCountData.new
但是在控制台上仍然没有定义,您似乎没有在尝试使用数据之前等待加载完成:
// This has a get call, which is async (takes time to load)
getFromServerScheduleCount(employees[key].schedule_employee_id);
// The script will continue, without waiting for the load to finish, so can be empty
console.log(scheduleCountData);
我建议添加回调,如下所示:
getFromServerScheduleCount(employees[key].schedule_employee_id, function(scheduleCountData) {
console.log(scheduleCountData);
});
看起来您正在将数据设置为
scheduleCountData.new
呈现页面时从控制台返回什么。log
很抱歉,我在这一行代码上写错了问题,我真的写了scheduleCountData.new,但控制台中仍显示未定义的scheduleCountData
的值是什么?完成我所期望的数据我试图帮助您认识到这是一个异步问题,但我认为我没有理解抱歉。您需要等待数据,还要避免对状态使用超出本地范围的参数scheduleCountData
是一种非常糟糕的代码味道,这意味着你很快就会自食其果。对于这个建议,我使用这个答案作为参考,我的工作现在继续