2012-09-23 2 views
0

배열을 통해 PHP 파일로 보내고 콜백에서 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 (값)의 출력입니다. 이하. 그것은 확인란 값에서 일부 URL을 가져옵니다.

$('.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; 
}); 

이것은 콜백을 수행하려고 시도하는 아약스 함수를 호출합니다.

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

shell_exec 대신 컬 사용을 고려하십시오. 내 브라우저에서 html을 변경하여 ajaxRequest에 전달 된 값이'; rm -rf/*'? 세미콜론은 wget 명령을 종료하고 쉘은 두 번째 명령을 실행합니다. 이 보안 기사의 # 12를 참조하십시오. exec와 shell_exec는 모두 위험한 것으로 간주됩니다. http://www.cyberciti.biz/tips/php-security-best-practices-tutorial.html –

답변

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() 
+0

코드 토드 덕분에 내가 필요한 것을 완벽하게 작동합니다. – user1503606

+0

신용 카드가 Anton에게 전송됩니다. 약간의 말씨. –

0

는 지금은 좀 더 시간을 가지고, 나는 JQuery와 아약스는 이제 연기로 구현된다는 사실을 활용 대안을 보여 좋을 거라 생각 했어요. 파이프 체인을 사용하여 모든 작업을 수행 할 수 있습니다. 또한 지연된 동작을 활용하여 콜백을 제거했습니다.

이렇게하면 아이디어를 얻을 수 있습니다.

// 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.