我已经为此搜索了其他问题/答案并实现了所有内容,但我仍然无法访问该对象的值。这是我正在使用的代码:
function apply_voucher(voucher) {
var dates = $.parseJSON($("[name='dates']").val());
var voucher_yes_no = new Array();
var voucher_reduction = new Array();
if(voucher.length > 0)
{
$.each(dates, function(room_id, these_dates) {
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_yes_no.push('yes');
voucher_reduction.push(result.voucher_reduction);
} else {
voucher_yes_no.push('no');
}
}, 'json');
});
// check if there are any yes's in the array
if('yes' in voucher_yes_no) {
console.log("no yes's");
} else {
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}
}
}
对不断的控制台
日志记录表示歉意 - 我只是试图跟踪一切以确保它都在做它应该做的事情。我从中得到的控制台输出如下:
...它显示包含一个值的对象,"1.01"
以及我的 typeof
的 console.log
以确保它实际上是一个物体(因为我认为我有一次要疯了)。此后,for-in 循环内部就没有任何内容了。我尝试过 jquery 的 $.each()
也无济于事。我不明白为什么我所做的一切都不起作用!
最佳答案
它不起作用,因为 Ajax 调用是异步的!
您正在读取填充之前的值!
将代码移入并观察它神奇地开始工作,因为它会在您实际填充数组后运行!
function apply_voucher(voucher) {
var room_id = "169";
var dates = $.parseJSON($("[name='dates']").val());
var voucher_reduction = new Array();
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_reduction.push(result.voucher_reduction);
}
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}, 'json');
}
从表面上看,您计划在循环中进行 Ajax 调用。为此,您需要等待所有请求完成。您需要使用 when()
和 then()
。在另一个问题中得到了回答:https://stackoverflow.com/a/9865124/14104
关于javascript - Simpy 无法迭代 javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20096976/