JQuery AJAX вызов выполнить один раз функцию после завершения - PullRequest
0 голосов
/ 23 февраля 2012

Я в мобильном приложении.Я использую ajax-вызовы для получения данных от веб-сервера с этим кодом:

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

Я хочу, чтобы bill - OK отображался только один раз после того, как все данные вставлены в sqlite.

Ответы [ 2 ]

1 голос
/ 23 февраля 2012

попробуйте это:

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");
                    }                        
                }
            );
        });             
    });
}
0 голосов
/ 23 февраля 2012

попробуйте добавить:

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

EDIT

ОК, а как же:

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

$('#mycontent').append("bill - OK"); //this line outside the each() call
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...