原生JS
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url');
// 上传完成后的回调函数
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('上传出错');
}
};
// 获取上传进度
xhr.upload.onprogress = function(event) {
console.log(event.loaded)
console.log(event.total)
if (event.lengthComputable) {
var percent = Math.floor(event.loaded / event.total * 100);
document.querySelector("#progress .progress-item").style.width = percent + "%";
// 设置进度显示
console.log(percent)
}
};
xhr.send(fd);
<div id="progress">
<div class="progress-item"></div>
</div>
#progress {
height: 10px;
width: 300px;
border: 1px solid gold;
position: relative;
border-radius: 5px;
}
#progress .progress-item {
height: 100%;
position: absolute;
left: 0;
top: 0;
background: chartreuse;
border-radius: 5px;
transition: width .3s linear;
}
jquery ajax
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;
}
}
xhr:xhrOnProgress(function(e){
var percent = (e.loaded / e.total * 100) + '%';//计算百分比
console.log(percent);
$('.progress1').css('width',percent);
})