本文介绍了jQuery的"uploadProgress"不要在"$ .ajax"中触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手,现在,我正在从事文件上传.而且我想在每次上传图片时添加一些进度条.我在jQuery中使用了uploadProgress,但似乎不起作用.这是我的代码:

I am new to jQuery and now, I am currently working on file uploads. 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. 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?

推荐答案

根据 $.ajax() 引用,uploadProgress不是有效的选项.

According to the $.ajax() reference, uploadProgress is not a valid option.

而是使用xhr选项,它使您可以在ajax请求使用的XMLHttpRequest上设置进度侦听器.

Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.

此答案显示了如何执行此操作:

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
    }
});

这篇关于jQuery的"uploadProgress"不要在"$ .ajax"中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:35