I am trying to use a nested ajax call to populate a table, and once the table is built, use jQuery's dataTable plugin to pretty it up.
The problem I am running into is an order of operations question. When do I call the dataTable function so that I can be assured that the table is built AFTER the values are populated? When I try the following code, the dataTable is created before the rows are built.
<script type="text/javascript">
$(document).ready(functi开发者_如何学Con() {
$.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>
The dataTable is created before the rows are built because nested ajax request(to "http://totalrockregistration.com/feeds/songs.php") is executed asynchronously. And function makeLeaderTable starts to be executed before ajax-request is finished. So you can invoke makeLeaderTable on nested ajax`s success:
...
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();
}
});
}
});
...
精彩评论