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

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

问题描述:

我在移动应用程序。我使用AJAX调用从Web服务器接收数据与此代码:jquery 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的所有数据后,只显示一次。

+0

和你实际的问题是.. 。? – 2012-02-22 20:50:22

+0

账单 - 确定显示每一个插入到sqlite的帖子... 20次 – kosbou 2012-02-22 20:51:19

+0

将您的“账单 - 确定”行移到'$ .each'循环之外。 – SenorAmor 2012-02-22 21:01:49

试试这个:

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

THX这对我很有用 – kosbou 2012-02-22 21:12:45

尝试添加:

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

编辑

OK,怎么样:

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

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

没有不工作 – kosbou 2012-02-22 20:54:16

+0

这样的法案确定一次,但插入前完成 – kosbou 2012-02-22 21:01:25

+0

以及异步:假行? – aletzo 2012-02-22 21:02:24