【问题标题】:How to call Ajax within an Each loop without Async:false Jquery如何在没有 Async:false Jquery 的 Each 循环中调用 Ajax
【发布时间】:2020-07-20 16:56:19
【问题描述】:

我有以下 HTML 结构,我想用 Ajax 调用填充每个块,但是当我使用 async:false 时,它​​在 Jquery 3x 中不起作用

<ul class="tray" id="hiphop"></ul>
<ul class="tray" id="rnb"></ul>
<ul class="tray" id="afro"></ul>
<ul class="tray" id="blues"></ul>
<ul class="tray" id="dancehall"></ul>
<ul class="tray" id="rumba"></ul>
<ul class="tray" id="samba"></ul>
<ul class="tray" id="trap"></ul>
<ul class="tray" id="rap"></ul>

我想要执行的是:

  • 浏览 HTML 结构并检索所有 ID
  • 为每个 ID 向我的服务器文件发送请求并
  • 根据每个block的ID显示得到的结果

这是我最初的 JS 代码:

$('.tray').each(function(){
    $id = $(this).attr('id');
    $.ajax({
        type: 'GET',
        url: 'feed',
        data: 'c='+$id,
        cache: false,
        // async: false, 
        success:function(datas){
            $('#'+$id+'').html(datas);=
        },
        error:function (){
            console.log('error ...');
        }
    });
});

但是在阅读了一个叫做 Promise 的东西之后,我尝试了这个,但老实说,我什至不明白我在做什么

var $array = $.map($('ul.tray'), function(value, index) {
    return [value];
});

var promises = [];
$array.forEach(function(item) {
    // you can access item.id and item.title here
    $id = $(this).attr('id');
    promises.push(
        $.ajax({
            type: 'GET',
            url: 'feed',
            data: 'c='+$id,
            cache: false,
        })
    );
});
Promise.all(promises).then(function(results) {
    // all ajax calls done here, results is an array of responses
    //console.log($results);
});

你能帮我在不使用异步的情况下用 Ajax 填充那些空块吗? 任何帮助将不胜感激

【问题讨论】:

    标签: jquery ajax loops asynchronous


    【解决方案1】:

    使用let 关键字定义对循环中元素的块范围引用,以便将其保留在AJAX 请求的回调中。试试这个:

    $('.tray').each(function() {
      let $tray = $(this);
    
      $.ajax({
        type: 'GET',
        url: 'feed',
        data: 'c=' + this.id,
        cache: false,
        success: function(datas) {
          $tray.html(datas);
        },
        error: function() {
          console.log('error...');
        }
      });
    });
    

    但是值得注意的是,在循环中发出 AJAX 请求并不是一个好习惯,因为它会很快地向服务器发送请求,并且不会随着并发站点访问而扩展。更好的方法是发出单个 AJAX 请求,该请求获取所有.tray 元素的数据并一次性更新它们。

    【讨论】:

    • 感谢@Rory 的回答,它运作良好。另外,如果您告诉我该怎么做,我可以采用您的方法
    猜你喜欢
    • 2020-06-05
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2016-09-20
    • 2010-12-15
    • 2013-06-14
    • 2018-10-08
    相关资源
    最近更新 更多