微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

可以使用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使用的函数

原文地址:https://www.jb51.cc/jquery/182758.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐