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非同期だからです。HTTPリクエストを開始するeachだけですが、すぐに返されるため、2console.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 に答える