2016-06-10 32 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