2013-10-24 2 views
2
function makeCall(file, handlerFile, sendMethod, formData) { 
    //console.log(instance.files); 

    $.ajax({ 
     url: handlerFile, 
     type: sendMethod, 
     xhr: function() { // Custom XMLHttpRequest 
      var xhr = $.ajaxSettings.xhr(); 

      if(xhr.upload) { // Check if upload property exists 
       xhr.upload.addEventListener('progress', progressHandlingFunction.bind(file)); // For handling the progress of the upload 
       //xhr.upload.addEventListener('loadend', successHandler.bind(xhr)); 
      } 

      //console.log(xhr); 

      return xhr; 
     }, 
     beforeSend: beforeSendHandler.bind(file), 
     success: completeHandler.bind(file), 
     //error: errorHandler, 
     data: formData, // Form data 
     dataType: 'json', 
     cache: true, 
     //async: false, 
     contentType: false, 
     processData: false 
    }); 

} 



$(".afu-input").on('change', function() { 
     var i = 0; 
     var length = this.files.length; 
     var files = this.files; 

     var calling = setInterval(function() { 
      var file = files[i]; 
      console.log(file); 

      uid = generateUniqueId(); 
      file.id = uid; 

      var formData = null; 
      formData = new FormData(); 

      formData.append(i, file); 
      formData.append(i, [uid]); 

      makeCall(file, handlerFile, sendMethod, formData); 

      i++; 

      if (i >= length) { 
       clearInterval(calling); 
      } 
     }, 2000); // Delay is for testing. Normaly there is no delay 
} 

하나씩 파일을 업로드하려고합니다. 하지만 문제는 아약스가 요청을 제대로 보내지 만 하나의 (첫 번째) 데이터 만 반환한다는 것입니다.Javascript, jQuery 동시에 여러 AJAX 요청

제 목표는 입력 [유형 = 파일] 변경시 이미지 (및 나중에 다른 파일)를 업로드하는 스크립트를 만드는 것입니다. 하나의 요청으로 여러 파일을 업로드하려했지만 진행 이벤트로 하나의 요청으로 등록했습니다. 나는 개미 조각으로 파일을 조각 (chunk)하는 것을 알고 있었지만,이 변형은 더 쉬워 보였다. (단지 그것을 작동시켜야한다. 감사.

+0

업로드가 2 초 지연되는 이유가 있습니까? – user1091949

+0

Nop, 테스트 용으로 문제를 찾고 2 초 지연을 추가했습니다. 어제 나는 인터넷 검색을 많이하고 jQuery에서 Deferred로 할 수 있다는 것을 알았습니다. 곧 테스트 할 것입니다. – TomasAchmedovas

답변

4

그것은 어떤 숫자가 될 수 있습니다 jQuery.when();

아약스 통화로를 쉽게 만들 수 있습니다. 따라서 apply()와 함께 사용해야한다. 아약스 호출 배열을 작성하십시오. 이제 코드는 다음과 같습니다.

function makeCall(file, formData) { 
    return $.ajax({ // It's necessary to return ajax call 
     url: 'handler.php', 
     type: 'POST', 
     xhr: function() { // Creating custom XHR to register progress event(If you know better solution - please post ir) 
      var xhr = $.ajaxSettings.xhr(); 

      if (xhr.upload) { // Check if upload property exists 
       xhr.upload.addEventListener('progress', progressHandlingFunction.bind(file)); // Registering progress event 
      } 

      return xhr; 
     }, 
     // Events handlers 
     beforeSend: beforeSendHandler.bind(file), 
     success: completeHandler, 
     data: formData, 
     dataType: 'json', 
     cache: true, 
     contentType: false, 
     proccessData: false 
    }); 
} 

$('.afu-input').on('change', function() { 
    var files = this.files; 
    var calls = []; 

    $.each(files, function(i, file) { 
     uid = generateUniqueId(); 
     file.id = uid; 

     var formData = new formData(); 

     formData.append(0, file); // Just easier to set index to 0 cause for every file returning new obejct, so is no point to set more indexes 

     calls.push(makeCall(file, formData)); // And finally pushing calls to array 
    }); 

    // Using jQuery.when 
    // Cause I don't know how many calls will be I'm using "apply" so I can add array instead of one by one calls 
    $.when.apply($, calls); // Exactly I don't know why need "$" 
} 

function beforeSendHandler() { 
    console.log(this); 
} 

function completeHandler(data) { 
    console.log(data); 
} 

function progressHandlingFunction(e) { 
    console.log(e); 
    console.log(this); 
} 
+0

Hooow,이 스크립트는 굉장합니다. – Ahmad