如果数据库更新成功,如何一个接一个地向页面提交多个jquery帖子?

时间:2013-05-25 21:17:52

标签: php jquery

我正在尝试将多个$ .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);
        });
    });

}
});
});

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

1 个答案:

答案 0 :(得分: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;
            });

        }
    });
});