dco*_*llo 25 ajax jquery xmlhttprequest progress
正如这里建议的那样:https://gist.github.com/HenrikJoreteg/2502497,我正在尝试为我的jQuery.ajax()文件上传添加onprogress功能.上传工作正常,并且onprogress事件正在触发,但不是我预期的 - 不是在某个时间间隔重复触发,它只在上传完成时触发一次.有没有办法指定onprogress刷新的频率?或者,我是否正在尝试做一些无法做到的事情?这是我的代码:
$.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!');
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
Get*_*ree 65
简答:
不,你不能做你想要的xhrFields.
答案很长:
XmlHttpRequest对象中有两个进度事件:
响应进度(XmlHttpRequest.onprogress)
这是浏览器从服务器下载数据的时间.
请求进度(XmlHttpRequest.upload.onprogress)
这是浏览器将数据发送到服务器时(包括POST参数,cookie和文件)
在您的代码中,您正在使用响应进度事件,但您需要的是请求进度事件.这是你如何做到的:
$.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,
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 ;
}
});
Run Code Online (Sandbox Code Playgroud)
该xhr选项的参数必须是返回jQuery来使用原生XMLHttpRequest对象的.
| 归档时间: |
|
| 查看次数: |
40296 次 |
| 最近记录: |