简体   繁体   English

jQuery的“uploadProgress”没有在“$ .ajax”中触发

[英]jQuery's “uploadProgress” not firing in “$.ajax”

I am new to jQuery and now, I am currently working on file uploads. 我是jQuery的新手,现在,我正在处理文件上传。 And I want to add some progress bar each time I upload image. 我想在每次上传图片时添加一些进度条。 I used the uploadProgress in jQuery but it seems doesn't work. 我在jQuery中使用了uploadProgress ,但它似乎不起作用。 Here's my code: 这是我的代码:

$('#_form_').on('submit', function(e){

   var file_and_desc = new FormData($(this)[0]),
       form_url = "_pages/_form_";

       var ext = choose.val(),
           allowed = ['jpg','png'];

       if(ext){
          var get_ext = ext.split('.');
              get_ext.reverse();

              if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
                   //upload image
                   $.ajax({
                         url : form_url,
                         type: 'POST',
                         data: file_and_desc,
                         contentType: false,
                         processData: false,
                         uploadProgress: function(event, positio, total, percentComplete){
                          $('h1').html(percentComplete);
                         },
                         success: function(data){
                              // some code here...
                         }
                   });
              }
       }
});

That's it! 而已! What should I do? 我该怎么办?

According to the $.ajax() reference, uploadProgress is not a valid option. 根据$.ajax()引用, uploadProgress不是有效选项。

Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request. 而是使用xhr选项,它允许您在ajax请求使用的XMLHttpRequest上设置进度侦听器。

this answer shows how to do that: 这个答案显示了如何做到这一点:

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                //Do something with upload progress here
            }
       }, false);
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM