您的位置:首页 > 运维架构

监控ajax上传进度

2018-11-30 16:17 39 查看
[code]<div id="open_content" style="padding:20px;">
<!-- 外层div 进度条的整体视觉和位置设置 -->
<div style="width:300px;height: 20px;border: 1px solid #CCC;">
<!-- 内层div  逐渐递增的进度条 -->
<div id="jdt" style="height: 20px;"></div>
</div>
<div style="margin-top:16px;">
<p style="margin-top:16px;">总大小<span id="total"></span>;</p>
<p style="margin-top:16px;">已上传<span id="loaded"></span>;</p>
</div><br>
</div>

 

[code]        $.ajax({
url: "${pageContext.request.contextPath}/base/add",
type: 'post',
cache: false,
data: formData,
processData: false,
contentType: false,
async : true,//这一步很重要,必须同步,异步监测不到
success: function (data) {

},
xhr: xhrOnProgress(function(evt){
var percent = Math.floor(evt.loaded / evt.total*100);//计算百分比
console.log(percent);
// 设置进度条样式
$('#jdt').css('width',percent * 3 + 'px');
$('#jdt').css('background','skyblue');
//显示进度百分比
$('#jdt').text(percent+'%');
$('#loaded').text(evt.loaded/1024 + 'K');
$('#total').text(evt.total/1024 + 'K');
}),
error: function(){

},
beforeSend: function(){

}
});
[code]var xhrOnProgress=function(fun) {
xhrOnProgress.onprogress = fun; //绑定监听
//使用闭包实现监听绑
return function() {
//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
var xhr = $.ajaxSettings.xhr();
//判断监听函数是否为函数
if (typeof xhrOnProgress.onprogress !== 'function')
return xhr;
//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
if (xhrOnProgress.onprogress && xhr.upload) {
xhr.upload.onprogress = xhrOnProgress.onprogress;
}
return xhr;
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: