简体   繁体   中英

jquery ajax call execute once function after complete

I am in mobile app. I use ajax calls to receive data from webserver with this code:

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

I want bill - OK displayed only once after all data inserted into sqlite.

try this:

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");
                    }                        
                }
            );
        });             
    });
}

try to add:

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

EDIT

OK, what about:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM