0

有谁介意给我解释一下为什么...

$(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);
});

我试图找到创建和存储多个对象的最佳方法。

4

2 回答 2

3

这是因为$.post是异步的。each唯一启动 HTTP 请求,但它立即返回,因此当第二次运行时,该console.log项目尚未创建。

于 2012-06-03T01:59:27.903 回答
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, ...);
于 2012-06-03T02:04:48.220 回答