开发者

jQuery: Possible to wait for $.get to finish loading before continuing?

开发者 https://www.devze.com 2022-12-12 11:50 出处:网络
The folowing script does not wait for $.get to finish loading the page before continuing with the loop:

The folowing script does not wait for $.get to finish loading the page before continuing with the loop:

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

data is a JSON object

Any ideas or comments will be greatly appreciated.


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

That should do it.

Old docs

2021 docs


If you didn't want to potentially lock the browser, you could do it this way which just keeps chugging through songs until they are all processed.

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

Note, it does alter the data.songs array by removing items upon processing. If this is a problem, duplicate the array before starting so it removes elements from the duplicate array.

On a side note, I am assuming you didn't paste all your code... right now it loads the same page for every song, but nothing from the song item is being used to alter the request in any way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号