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

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

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

data是一个JSON对象

任何想法或意见将不胜感激。

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

应该这样做。

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

如果您不想潜在地锁定浏览器,您可以通过这种方式进行操作,这样就可以一直处理歌曲,直到它们全部被处理完毕。

 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项目中没有任何内容用于以任何方式更改请求。