开发者

make ajax wait until each with get is finished

I have a jquery .each loop with a .get inside. I want to wait until all gets inside the loop are completed (each get pushes at .complete a new element into an array) and then make an ajax post request to a php file to save the created array. I don't know how I can make the ajax request wait until the each is finished. Until now the aja开发者_StackOverflowx fires very quickly and therefore the array is still empty as the gets inside the each are still not finished when it fires. Maybe you have an idea.

Here is the script:

$('#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;

});

I appreciate any help. Thank you :)


Underscore.js has an 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜