【问题标题】:make ajax wait until each with get is finished让 ajax 等到每个 get 完成
【发布时间】:2011-08-09 15:54:23
【问题描述】:

我有一个带有 .get 的 jquery .each 循环。我想等到循环内的所有内容都完成(每个 get 将 .complete 一个新元素推送到数组中),然后向 php 文件发出 ajax 发布请求以保存创建的数组。我不知道如何让 ajax 请求等到每个完成。到目前为止,ajax 触发非常快,因此数组仍然是空的,因为每个内部的 get 在触发时仍未完成。也许你有一个想法。

这是脚本:

$('#ScanButton, .ScanButton').click(function() {

var array = ["http://www.xyz.com/bla/bla/summary.html",
             "http://www.xyz.com/blu/blu/summary.html",
            ];

dataArray = [];

$.each(array, function(n, val) { 


    $.get(val, function(res) { //get the html source of this website



      var data = {

      }

  }).complete(function() { 
        alert("complete"); 
        dataArray.push(data);
    });

});

    data = YAHOO.lang.JSON.stringify(dataArray);      

  $.ajax({
    async:           false,
    type:           'post',
    cache:          false,
    url:            'test.php',
    data:           {myJson:  data}
    });

  return false;

});

感谢您的帮助。谢谢你:)

【问题讨论】:

  • “同源策略”是否会成为问题,因为 .get() 函数是 .ajax() 的简写函数,受此影响。有关这方面的更多信息,请访问en.wikipedia.org/wiki/Same_origin_policy?希望对您有所帮助。
  • 我熟悉同源策略的概念。谢谢!:) 我有一个可行的解决方法(它仅适用于私人项目)。但是直到现在,在每个循环之后,都会触发 ajax 发布请求。我想将这些请求减少到一个。这就是为什么最后一个 ajax post 请求应该在循环完成并且数组完成传递之后触发的原因。

标签: ajax get each activity-finish


【解决方案1】:

Underscore.js 有一个elegant solution to this sort of problem

var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
  note.asyncSave({success: renderNotes}); 
});
// renderNotes is run once, after all notes have saved.

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2012-01-29
    • 2014-07-14
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多