2016-06-10 57 views
0

我這樣做,它工作出色

$.ajax({ 
    url : 'php/upload.php', 
    xhr: function(){ 
     var xhr = new XMLHttpRequest(); 
     xhr.upload.addEventListener("progress", function (e) { 
      $('#upload-progress-bar-1').animate({   
       'width': (Math.round(e.loaded/e.total) * 100) + '%'}, 400); 
      }, false); 
      return xhr;  
     }, 
     data : this.formData, 
     type : 'POST', 
     processData: false, 
     contentType: false, 
     dataType: "json", 
     success : function(data) { 
      //$('#upload-progress-bar-1').css('width', '100%'); 
     } 
    }); 

的問題是,$('#upload-progress-bar-1')將是動態的,但我無法弄清楚如何通過一個參數放入xhr:回調函數中。

任何人都知道這樣做的方式?

+1

您不能爲該功能提供任何參數。您需要在'$ .ajax'請求的範圍內聲明一個變量,並在'xhr'屬性中檢索它。 –

+0

所以如果我添加id到表單數據,比如'this.formData.append('progressBarID',this.progressBarID);'我可以在xhr回調中以某種方式檢索它嗎?像'xhr.get('progressBarID')'? – user2287474

+0

定義一個全局變量並在'ajax'發生之前更新它的值。那麼在你的回調函數裏你可以得到它。 –

回答

1

使用局部變量,並在回調中引用它。

var target = $("#upload-progress-bar-1"); 
$.ajax({ 
    url : 'php/upload.php', 
    xhr: function(){ 
     var xhr = new XMLHttpRequest(); 
     xhr.upload.addEventListener("progress", function (e) { 
      target.animate({   
       'width': (Math.round(e.loaded/e.total) * 100) + '%'}, 400); 
     }, false); 
     return xhr;  
    }, 
    data : this.formData, 
    type : 'POST', 
    processData: false, 
    contentType: false, 
    dataType: "json", 
    success : function(data) { 
     target.css('width', '100%'); 
    } 
}); 
+0

這是有道理的。謝謝!! – user2287474