通过回调循环数组

时间:2012-09-23 13:39:43

标签: javascript jquery ajax arrays callback

我正在尝试通过数组发送到php文件并在回调上发送完成下载后的下一个值。这就是我到目前为止所拥有的。

我的阵列如下:

["http://example.com/test1.zip", "http://example.com/test2.zip", "http://example.com/test3.zip", "http://example.com/test4.zip", "http://example.com/test5.zip"] 

以上是console.log(values)的输出;下面。它从复选框值中抓取一些网址。

$('.geturls').live('click',function(){

    var values = new Array();
    $.each($("input[name='downloadQue[]']:checked"), function() {
      values.push($(this).val());

       ajaxRequest($(this).val(),function(response){

            console.log(response);

       });  

    });

    console.log(values);

    return false;
});

然后调用ajax函数,我正在尝试进行回调。

function ajaxRequest(urlSend,callback){

    var send = {
            url: urlSend
        }

    $.ajax({
          type: "POST",
          url: "<?php echo base_url(); ?>index.php/upload",
          data: send,
          //dataType: "json",
          //timeout: 8000,
          beforeSend: function() {

          },
          success: function(response) {

             callback('added');

          },
          error: function (response) {

                     callback('false');

          }
     });


}

然后发送到php文件。

function upload(){
   $output = shell_exec("wget {$_POST['url']} 2>&1");      
   return true;
}

我想要做的是从完全下载的一个url的回调之后,然后从数组中获取下一个值并下载该URL,依此类推,直到数组中的所有url都被完全下载。

此刻它只是下载第一个值然后崩溃,因为它在返回值返回true后没有重新启动循环。

希望这对于那些只是寻求一些帮助的人来说是有意义的,这些帮助是关于在完成后通过回调循环遍历数组值的最佳方法。

2 个答案:

答案 0 :(得分:2)

可能这个结构可以帮到你。在此变体中,只有在成功完成上一个Ajax调用后才会转到下一个URL。

    var arr = ['url0','url1','url2','url3'];
    var index = 0;

    function Run(){
         DoAjax(arr[index]);
    }
    function Next( ){
        if(arr.count = index-1)
        {
             index =0;
             return;  
        }else{
           DoAjax(arr[index ]);
        }
    }    

    function DoAjax(url){

         $.ajax({
          type: "POST",
          url: url,
          data: send,
          beforeSend: function() {

          },
          success: function(response) {
             index ++;
             Next();
             // Addition logic if needed
          },
          error: function (response) {

          }
     });
    }

Run()

答案 1 :(得分:0)

现在我有更多的时间,我认为展示一个利用jquery ajax现在实现为延迟的事实的替代方案会很好。这意味着您可以使用管道链为您完成所有工作。我也通过利用延期行为来消除回调。

这应该会给你一个想法。

// Use jquery deferred pipe chaining to force 
// async functions to run sequentially


var dfd = $.Deferred(),
    dfdNext = dfd,
    x,
    values = [],

    // The important thing to understand here is that 
    // you are returning the value of $.ajax to the caller.
    // The caller will then get the promise from the deferred.
    ajaxRequest = function (urlSend) {

        var send = {
            url: urlSend
        }

        return  $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>index.php/upload",
            data: send,
        });
    };


// Starts things running.  You should be able to put this anywhere 
// in the script, including at the end and the code will work the same.

dfd.resolve();


// Deferred pipe chaining.  This is the main part of the logic.
// What you want to note here is that a new ajax call will 
// not start until the previous
// ajax call is completely finished.
// Also note that we've moved the code that would
// normally be in the callback.
// Finally notice how we are chaining the pipes by
// replacing dfdNext with the return value from the
// current pipe.
for (x = 1; x <= 4; x++) {

    values.push(x);

    dfdNext = dfdNext.pipe(function () {
        var value = values.shift();
        return requestAjax(value).
            done(function(response) {
                // Code here that you would have 
                // put in your callback.
                console.log(response);
            }).
            fail(function(response) {
                console.log(response);
            };

    });

}

工作示例you can play with on jsFiddle