ajax获取上传进度的值

 $.ajax({
        url: 'URL',
        type: 'POST',
        data: fd,
        processData: false, //用来回避jquery对formdata的默认序列化,XMLHttpRequest会对其进行正确处理  
        contentType: false, //设为false才会获得正确的conten-Type  
        xhr: function() { //用以显示上传进度  
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function(event) {
                    var percent = Math.floor(event.loaded / event.total * 100); //进度值(百分比制)
                    document.querySelector("#progress .progress-item").style.width = percent + "%";
                }, false);
            }
            return xhr
        },
        success: function(data) {

        }
    })

原生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);

你可能感兴趣的:(ajax)