首页 > 解决方案 > Ajax 进度条,直到我的成功功能完成

问题描述

我正在实现一个 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%,直到我的成功功能被执行。

标签: jqueryajax

解决方案


像下面这样尝试,所以只有在完成后才会 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){

        }
    });

推荐阅读