【问题标题】:Loop through a list of elements & send data by ajax循环遍历元素列表并通过 ajax 发送数据
【发布时间】:2018-07-21 22:53:05
【问题描述】:

我有一个 li 元素列表。每个 li 元素都包含一些文本段落。

要查看一个元素的内容,我的应用应该点击这个li元素,然后一个弹出窗口是打开,应用程序从弹出窗口中检索文本,然后使用 $.ajax 将其发布到服务器。

为此,我使用 each 方法 逐个循环所有 li 元素。 我的目的是找到一种 jquery 或 javascript 方式来等待每次从 li 元素中检索信息,然后当使用 ajax 发布所有数据时,移动到下一个 li 等等。

listItem.each(function(index) {
  if (myCondition) {
    console.log('item with index: ' + index + ' is skipped');
  } else {
    listItem.click();
    setTimeout(function() { // Wait 1 second until the popup is opended
      popupWindow.animate({
        scrollTop: $(this).height()
      }, $(this).height() * 10, getData);

      function getData() {
        // ...
        // ...
        postData(data);
      }
    }, 1000);
  }
});

function postData(data) {
  $.ajax({
    type: 'POST',
    // ...
    // ...
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="myList">
  <li class="list-item">.......</li>
  <li class="list-item">.......</li>
  <li class="list-item">.......</li>
  <!-- ...... -->
</ul>

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    您可以递归调用处理一项并在 ajax 承诺解析中传入 next() 的函数,而不是循环

    // initial call
    processItem($('.myList li:first'));
    
    function processItem($li) {
      if (!$li.length) {
        return; // none left
      }
    
      var $next = $li.next();
    
      if (condition) {
        console.log('item with index: ' + $li.index() + ' is skipped');
        // recursive call assumed here also
        processItem($next);
    
      } else {
        $li.click();
        setTimeout(function() { // Wait 1 second untill the popup is opended
          popupWindow.animate({
            scrollTop: $(this).height()
          }, $(this).height() * 10, getData);
    
          // get the data to post
    
          // use promise returned from postData to start process next item
          postData(data).then(function() {
            processItem($next)
          });
    
        }, 1000);
      }
    }
    
    
    function postData(data) {
    // must return the ajax promise 
     return $.ajax({
        type: 'POST',
        // ...
        // ...
      });
    }
    

    【讨论】:

    • 谢谢@charlietfl!现在看来工作得很好。
    • 太棒了...担心我可能会错过一些小事。当您无法自己测试时会更棘手
    【解决方案2】:

    您可能会在每个$.ajax 电话中await。使用for 循环代替listItem.each(它将迭代同步),它允许简单的串行异步。请注意,您必须在 async 函数中才能使用 await。例如:

    (async () => {
      for (const li of $('.list-item')) {
        await $.ajax( ... )
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2018-07-11
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      相关资源
      最近更新 更多