【问题标题】:Ajax progress bar until my success function is finishedAjax 进度条,直到我的成功功能完成
【发布时间】:2019-06-14 21:15:44
【问题描述】:

我正在实现一个 ajax 进度条,我希望在我的 ajax 成功函数完成之前进度不会达到 100%。

    $.ajax({

        data: //data,
        type: 'post',
        url: url,
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
            var elem = document.getElementById("myBar");
                var width = 10;
                var id = setInterval(frame, 10);
            function frame() {
                if (width >= 100) {
                   clearInterval(id);
                } 
                            else {
                   width++; 
                   elem.style.width = width + '%'; 
                   elem.innerHTML = width * 1  + '%';                               
                    }
                   }
         return xhr;
},
success: // code
        };

我的 ajax 进度条显示 100% ,但仍然等到成功功能完成。所以,我正在寻找在我的成功函数执行之前我的进度条不应该达到 100%。

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    像下面这样尝试,所以只有完成后才会 100%。

    html

    <progress></progress>
    

    jQuery 代码

    $.ajax({
            url: url,
            type: 'POST',
            enctype: 'multipart/form-data',
            //Form data
            data: new FormData($('#fileupload-form')[0]), // Data sent to server, a set of key/value pairs representing form fields and values
            // Tell jQuery not to process data or worry about content-type
            // You *must* include these options!
            cache: false, // To unable request pages to be cached
            contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
            processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
            //Custom XMLHttpRequest
            xhr: function(){
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    // For handling the progress of the upload
                    myXhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            $('progress').attr({
                                value: e.loaded,
                                max: e.total,
                            });
                        }
                    } , false);
                }
                return myXhr;
            },
            success: function(res){
    
            }
        });
    

    【讨论】:

    • 感谢您的评论,我试过了。但它直接在 ajax 调用中将我的加载栏从 10% 加载到 100%。即使我的 ajax 调用需要一些时间。
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2012-08-21
    • 1970-01-01
    • 2018-10-13
    • 2013-05-20
    • 2014-10-09
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多