有人会介意向我解释为什么......
$(document).ready(function() {
var scu = ['0291285', '0409338', '0521704', '0521990', '0523652', '0523657', '0523660', '0523704'];
var inData = $('#output');
var testdiv = $('#testdiv');
function Item(scu, description, price, extended, type) {
this.scu = scu;
this.description = description;
this.price = price;
this.extended = extended;
this.type = type;
//this.saved = function() {};
}
var rows = [];
function get() {
inData.html('');
$.each(scu, function(index, val) {
$.post('chBuild.php', {scu:val}, function(output) {
$.each(output, function(i, obj) {
var i = 0;
rows[i] = new Item(obj.scu, obj.description, obj.price, obj.extended, obj.type);
console.log(rows[i].price)
//this logs every object but...
i =+ 1;
});
}, 'json');
});
console.log(rows[0].price);
//this says rows[0] is undefined?
}
inData.click(get);
});
我正在尝试找到创建和存储多个对象的最佳方法。
答案 0 :(得分:3)
因为$.post
是异步的。 each
仅启动HTTP请求,但它立即返回,因此当第二个console.log
运行时,尚未创建项目。
答案 1 :(得分:3)
$.post('chBuild.php', {scu:val}, function(output) {
$.each(output, function(i, obj) {
var i = 0;
rows[i] = new Item(obj.scu, obj.description, obj.price, obj.extended, obj.type);
console.log(rows[i].price)
i =+ 1;
});
}, 'json');
这里对$ .post的调用是异步的,将在ajax调用返回时填充。也许你应该让它同步
$.ajax({'url': 'chBuild.php', 'async': false, ...);