2015-09-27 66 views
1

我使用this Stackoverflow question的代碼。出於某種原因,上傳開始時,百分比值停留在1%,並且在完成上傳後,成功消息將顯示在PHP腳本中。FormData進度卡住在1%

請注意,爲什麼百分比值停留在1%。

jQuery代碼

function updateProgress(evt){ 
    if (evt.lengthComputable) { 
     var percentComplete = evt.loaded/evt.total; 
     $('form[data-submit="ajax_upload_mp3"] .validation').html(percentComplete + '% Completed').addClass('text-success'); 
    } 
} 

$(document).on('submit', 'form[data-submit="ajax_upload_mp3"]', function(){ 
    wrap = 'form[data-submit="ajax_upload_mp3"]'; 
    button = 'form[data-submit="ajax_upload_mp3"] .btn-primary'; 
    url = $(this).attr('action'); 
    form = $(this); 
    formdata = new FormData(form[0]); 
    $(wrap + ' .validation').html('').removeClass('text-danger text-success'); 
    $(wrap + ' .btn-primary').html('Uploading...').attr('disabled', true); 
    $.ajax({ 
     url: url, 
     data: formdata ? formdata : form.serialize(), 
     cache: false, 
     contentType: false, 
     processData: false, 
     type: 'POST', 
     xhr: function(){ 
      myXhr = $.ajaxSettings.xhr(); 
      if(myXhr.upload){ 
       myXhr.upload.addEventListener('progress', updateProgress, false); 
      } 
      return myXhr; 
     }, 
     success: function(data, textStatus, jqXHR){ 
      code = ajax_decode(data, 0); 
      msg = ajax_decode(data, 1); 
      if(code == 1){ 
       $(wrap + ' .validation').html(msg).addClass('text-success'); 
       $(wrap).trigger("reset"); 
      } else { 
       $(wrap + ' .validation').html(msg).addClass('text-danger'); 
      } 
      $(wrap + ' .btn-primary').html('Upload').attr('disabled', false); 
     } 
    }); 
    return false; 
}); 

回答

1

這裏:

if (evt.lengthComputable) { 
    var percentComplete = evt.loaded/evt.total; 
} 

它不是一個百分比(如50%),它是一個部門(如0.5
這就是爲什麼它永遠不會超過1

如果你想顯示百分比,你需要100乘以:

var percentComplete = evt.loaded/evt.total * 100; 

就這麼簡單:)