【问题标题】:jQuery: Possible to wait for $.get to finish loading before continuing?jQuery:在继续之前可以等待 $.get 完成加载吗?
【发布时间】:2010-12-18 04:47:15
【问题描述】:

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

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

数据是一个 JSON 对象

任何想法或 cmets 将不胜感激。

【问题讨论】:

    标签: javascript jquery json loops


    【解决方案1】:
    $.ajax({
         async: false,
         type: 'GET',
         url: 'http://localhost/play.php',
         success: function(data) {
              //callback
         }
    });
    

    应该可以的。

    Old docs

    2021 docs

    【讨论】:

    • 只是让 OP 知道,从上面的链接:“请注意,同步请求可能会暂时锁定浏览器,在请求处于活动状态时禁用任何操作。”
    • 这可行,但也会在我的 Chrome 浏览器中发出此警告:pace.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.。显然这是因为设置了async: false。有什么想法可以消除这个警告吗?
    【解决方案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 项目中的任何内容都没有用于更改以任何方式请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      相关资源
      最近更新 更多