jQuery:可以在继续之前等待$ .get完成加载吗?

时间:2009-11-19 07:03:29

标签: javascript jquery json loops

在继续循环之前,下面的脚本不会等待$ .get完成加载页面:

$.each(data.songs, function(index, val) {
    $('#nowartist')
         .append('song starting');
    $.get("http://localhost/play.php", function(data){
         alert('done');
    });
});

数据是JSON对象

非常感谢任何想法或评论。

2 个答案:

答案 0 :(得分:56)

$.ajax({
     async: false,
     type: 'GET',
     url: 'http://localhost/play.php',
     success: function(data) {
          //callback
     }
});

应该这样做。

http://docs.jquery.com/Ajax/jQuery.ajax#options

答案 1 :(得分:2)

如果你不想潜在地锁定浏览器,你可以这样做,只是一直在浏览歌曲,直到它们全部被处理完毕。

function play_next(){
   var song = data.songs.shift(); // Removes the first song and stores it in song

   $('#nowartist').append('song starting');

   $.get("http://localhost/play.php", function(ret_data){
      alert('done');
      if(data.songs.length) play_next(); // Call next song if more songs exist;
   });
}
play_next(); // Start it off

注意,它会通过在处理时删除项目来更改data.songs数组。如果这是一个问题,请在开始之前复制数组,以便从重复数组中删除元素。

在旁注中,我假设您没有粘贴所有代码...现在它为每首歌加载相同的页面,但song项目中没有任何内容被用于以任何方式改变请求。

相关问题