2009-11-19 155 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項目中的任何內容都不用於在任何情況下更改請求辦法。

相關問題