使用jQuery的dataTable插件和嵌套的Ajax调用

时间:2010-04-28 23:19:55

标签: jquery ajax json datatable nested

我正在尝试使用嵌套的ajax调用来填充表,一旦构建了表,使用jQuery的dataTable插件来完善它。

我遇到的问题是操作顺序问题。我何时调用dataTable函数以便确保在填充值后构建表?当我尝试以下代码时,将在构建行之前创建dataTable。

<script type="text/javascript">
  $(document).ready(function() {
 $.ajax({
  url:"http://totalrockregistration.com/feeds/bands.php", 
  dataType:"jsonp", 
  success: function(jsonData){
   $.each(jsonData.bands, function(i,bands){
    if (bands.barID == "<?php echo $_GET["barID"]; ?>"){
     var songIdFromBandJson = bands.song;
     var bandNameFromJson = bands.name;
     var bandScoreFromJson = bands.score;
     $.ajax({
      url:"http://totalrockregistration.com/feeds/songs.php", 
      dataType:"jsonp", 
      success: function(songsJsonData){
       $.each(songsJsonData.songs, function(i,songs){
        if (songIdFromBandJson == songs.id){
         var songName=(songs.name);
         $("#leaderBoardTable tbody").append("<tr><td>"+bandNameFromJson+"</td><td>"+bandScoreFromJson+"</td><td>"+songName+"</td></tr>");
        }
       });
      }
     });
    }
   });
   makeLeaderTable();
  },
 });
 function makeLeaderTable(){
  $('#leaderBoardTable').dataTable({
   "aaSorting": [[ 1, "desc" ]],
   "iDisplayLength": 50
  });
 }

  });
</script>

1 个答案:

答案 0 :(得分:0)

在构建行之前创建了dataTable,因为嵌套的ajax请求(到“http://totalrockregistration.com/feeds/songs.php”)是异步执行的。函数makeLeaderTable在ajax-request完成之前开始执行。 所以你可以在嵌套的ajax成功时调用makeLeaderTable:

...    
success: function(jsonData){
   $.each(jsonData.bands, function(i,bands){
    if (bands.barID == "<?php echo $_GET["barID"]; ?>"){
     var songIdFromBandJson = bands.song;
     var bandNameFromJson = bands.name;
     var bandScoreFromJson = bands.score;
     var bandsCompleteCounter = jsonData.bands.length;
     $.ajax({
      url:"http://totalrockregistration.com/feeds/songs.php", 
      dataType:"jsonp", 
      success: function(songsJsonData){
       $.each(songsJsonData.songs, function(i,songs){
        if (songIdFromBandJson == songs.id){
         var songName=(songs.name);
         $("#leaderBoardTable tbody").append("<tr><td>"+bandNameFromJson+"</td><td>"+bandScoreFromJson+"</td><td>"+songName+"</td></tr>");
        }
       });
       if((--bandsCompleteCounter) == 0)
         makeLeaderTable();
      }
     });
    }
   });
...