可以使用xhrFields将进度功能添加到jQuery.ajax()中吗?

如我所建议的: https://gist.github.com/HenrikJoreteg/2502497,我正在尝试添加onprogress功能到我的jQuery.ajax()文件上传上传工作正常,进度事件正在触发,但不如预期的那样 – 而不是在某个时间间隔重复点火,当上传完成时,它只会触发一次。有没有办法指定进度刷新的频率?还是我试图做一些不能做的事情?这是我的代码
$.ajax(
{
    async: true,contentType: file.type,data: file,dataType: 'xml',processData: false,success: function(xml)
    {
        // Do stuff with the returned xml
    },type: 'post',url: '/fileuploader/' + file.name,xhrFields:
    {
        onprogress: function(progress)
        {
            var percentage = Math.floor((progress.total / progress.totalSize) * 100);
            console.log('progress',percentage);
            if (percentage === 100)
            {
                console.log('DONE!');
            }
        }
    }
});

解决方法

简答:
不,你不能使用xhrFields做你想要的。

长答案:

XmlHttpRequest对象中有两个进度事件:

>响应进度(XmlHttpRequest.onprogress)
这是当浏览器从服务器下载数据时。
>请求进度(XmlHttpRequest.upload.onprogress)
这是当浏览器将数据发送到服务器时(包括POST参数,Cookie和文件)

在您的代码中,您正在使用响应进度事件,但您需要的是请求进度事件。这是你如何做的:

$.ajax({
    async: true,success: function(xml){
        // Do stuff with the returned xml
    },xhr: function(){
        // get the native XmlHttpRequest object
        var xhr = $.ajaxSettings.xhr() ;
        // set the onprogress event handler
        xhr.upload.onprogress = function(evt){ console.log('progress',evt.loaded/evt.total*100) } ;
        // set the onload event handler
        xhr.upload.onload = function(){ console.log('DONE!') } ;
        // return the customized object
        return xhr ;
    }
});

xhr选项参数必须是返回一个本机XmlHttpRequest对象以供jQuery使用的函数

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...