0

我正在尝试将多个 $.post 发送到单个页面。我需要每个人都发布到更新数据库的页面,然后发布下一个,直到完成。到目前为止,这是我的代码:

$(document).ready(function(){
$("#action").change(function(){
var selectVal = $('#action :selected').val();
if(selectVal == "list-all"){

    $(".prelistCheckbox:checked").each(function(index) {
        var theValue = $(this).val();
        console.log('Values to be passed: ' + theValue);
        var form = $('form[id=' + theValue + ']');
        console.log(form.serialize());
//          $.post(form.attr('action'), form.serialize(), function(data) {
        $.post('jqueryPost.php', form.serialize(), function(data) {
            $('#results').text(data);
            console.log(data);
        });
    });

}
});
});

我真的不知道如何让它做到这一点。表单是从带有循环的数据库的行中生成的。

4

1 回答 1

0

延迟对象将在这里为您提供帮助:

$(document).ready(function(){
    $("#action").change(function(){
        var selectVal = $('#action :selected').val();
        if(selectVal == "list-all"){

            //define a variable where we will store deferred objects
            var def = true;

            $(".prelistCheckbox:checked").each(function(index) {
                var theValue = $(this).val();
                console.log('Values to be passed: ' + theValue);
                var form = $('form[id=' + theValue + ']');
                console.log(form.serialize());

                var postResult = $.Deferred();

                //.when take a deferred object as a param. 
                // if we pass not a deferred object .when treats it as resolved.
                // as our initial value of def=true, the first .when starts immediately
                $.when(def).then(function(){
                    $.post('jqueryPost.php', form.serialize(), function(data) {
                        $('#results').text(data);
                        console.log(data);
                    }).done(function(){
                        //the chain will fail after the first failed post request
                        //if you want all the requests to complete in any case change the above .done to .always
                        post.resolve();
                    });
                });

                // now we reassign def with th deferred object for the next post request
                def = postResult;
            });

        }
    });
});
于 2013-05-25T22:06:38.487 回答