Ajax调用进度百分比(指示符)

Ajax call percentage of progress (indicator)

本文关键字:指示符 百分比 调用 Ajax      更新时间:2023-09-26

我有一个数据类型为JSON的AJAX调用,当运行AJAX调用时,进度百分比在console.log中指示,但在磁盘上完成上传文件之前达到的百分比是100%。如何将百分比与流程的实际进度同步?我等待答案,谢谢!

JavaScript

$(document).on('click','.btnSend',function() {
        var imagem = $(this).closest('img.img-preview');
        if (imagem.length>0)
        {
            img_data = imagem.attr('src'); //base64
            img_size = imagem.attr('size');         
        }
        var myjson_imagem = JSON.stringify({img_data: img_data,img_size:img_size});
        $.ajax
        ({
            type: "POST",
            url: "ajax_upload.php",
            data: {dataimagem:myjson_imagem},
            datatype: 'json',
            complete: function(){
                $("[data-toggle='tooltip']").tooltip();
            },
            cache: false,
            async: true,
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.onprogress = function e() {
                    // For downloads
                    if (e.lengthComputable) {
                        console.log((e.loaded / e.total *100|0)+"%");
                    }
                };
                xhr.upload.onprogress = function (e) {
                    // For uploads
                    if (e.lengthComputable) {
                        console.log((e.loaded / e.total *100|0)+"%");
                    }
                };
                return xhr;
            },
            success: function(response)
            {
                console.log(response);                                                              
                var obj = JSON.parse(response);         
                var result = obj[0].ajax_result;
                switch (result)
                {
                    case "0": console.log('upload ok'); break;
                    case "1": console.log('upload not ok'); break;
                }
            },
            error: function()
            {
                alert('ajax error UPLOAD');
            }
        });
    });

记录

scriptx.js:1225 3%
scriptx.js:1225 97%
scriptx.js:1225 100%

我最近使用了一个类似的ajax函数,为文件上传器处理进度条。在上传完全完成之前,它达到100%,我没有遇到任何问题。我在下面列举了一个例子。

    xhr: function() {
                var xhr = $.ajaxSettings.xhr() ;
                // set the onprogress event handler
                xhr.upload.onprogress = function(evt) { 
                    let percentComplete = evt.loaded / evt.total*100+'%';
                    console.log(percentComplete);
};

我希望这能有所帮助。