2009-11-19 121 views
18

如下因素脚本不会等待$不用彷徨完成与循环在继续之前加载页面:

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

数据是JSON对象

任何意见或建议,将不胜感激。

回答

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

这应该做到这一点。

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

+3

正因如此,OP从上面的链接中了解到:“请注意,同步请求可能会暂时锁定浏览器,并在请求处于活动状态时禁用任何操作。” – 2009-11-19 07:12:32

+1

这可以工作,但也会在我的Chrome浏览器中发出警告:'''pace.min.js:2 [弃用]主线程上的同步XMLHttpRequest已弃用,因为它对最终用户的体验有不利影响。如需更多帮助,请查看https:// xhr.spec.whatwg.org/.'''。显然这是因为设置了'async:false'。任何可以消除此警告的替代方法? – tsando 2018-01-22 13:06:48

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项目中的任何内容都不用于在任何情况下更改请求办法。

相关问题