jquery ajax调用完成后执行一次函数

时间:2012-02-22 20:48:13

标签: javascript jquery ajax sqlite

我在移动应用中。我使用ajax调用通过以下代码从webserver接收数据:

            $.ajax({
                url: 'http://www.xxxxxxxxxxxx',
                data: {name: 'Chad'},
                dataType: 'jsonp',
                success: function(data){
                    $.each(data.posts, function(i,post){
                        $.mobile.notesdb.transaction(function(t) {
                        t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?);',
                            [post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.receiptno],
                            function(){ 
                                bill = 1;
                                $('#mycontent').append("bill - OK");
                            }
                        );
                        });             
                    });
                }
            });

我希望在所有数据插入sqlite后只显示bill - OK

2 个答案:

答案 0 :(得分:1)

试试这个:

success: function(data){

    var count = data.posts.length;

    $.each(data.posts, function(i,post){
        $.mobile.notesdb.transaction(function(t) {
            t.executeSql(<...>,
                function() { 
                    bill = 1;
                    if (--count == 0) {
                        $('#mycontent').append("bill - OK");
                    }                        
                }
            );
        });             
    });
}

答案 1 :(得分:0)

尝试添加:

$.ajax({
    url: 'http://www.xxxxxxxxxxxx',
    data: {name: 'Chad'},
    dataType: 'jsonp',
    async: false, //this line here
    //...

修改

好的,怎么样:

$.each(data.posts, function(i,post){
    //rest of stuff
});

$('#mycontent').append("bill - OK"); //this line outside the each() call