Javascript Jquery::Ajax 驱动的进度条?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4503658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:40:04  来源:igfitidea点击:

Jquery:: Ajax powered progress bar?

phpjavascriptjqueryajaxprogress-bar

提问by Hailwood

I have a page which uses jquery's ajax functions to send some messages.

我有一个页面,它使用 jquery 的 ajax 函数来发送一些消息。

There could be upwards of 50k messages to send.

可能有多达 50k 条消息要发送。

This can take some time obviously.

这显然需要一些时间。

What I am looking to do is show a progress bar with the messages being sent.

我想要做的是显示一个带有正在发送的消息的进度条。

The backend is PHP.

后端是PHP。

How can I do this?

我怎样才能做到这一点?



我的解决方案:通过原始 ajax 调用中的唯一标识符发送。


该标识符与完成百分比一起存储在数据库(或以标识符命名的文件等)中。

This is updated as the original script proceeds.

这是随着原始脚本的进行而更新的。

a function is setup called progress(ident)

一个函数被设置调用 progress(ident)

The function makes an ajax call to a script that reads the percentage.
the progressbar is updated If the returned percentage is not 100,
the function sets a timeout that calls itself after 1 second.

该函数对读取百分比的脚本进行 ajax 调用。
进度条更新 如果返回的百分比不是 100,则
该函数设置一个超时,在 1 秒后调用自身。

采纳答案by 65Fbef05

You could have an animated gif load via .html()into the results area until your ajax function returns back the results. Just an idea.

您可以将动画 gif 加载.html()到结果区域,直到您的 ajax 函数返回结果。只是一个想法。

Regarding the jquery ui progress bar, intermittently through your script you'll want to echo a numeric value representing the percent complete as an assigned javascript variable. For example...

关于 jquery ui 进度条,间歇性地通过您的脚本,您需要将表示完成百分比的数值作为分配的 javascript 变量进行回显。例如...

// text example php script
if (isset($_GET['twentyfive-percent'])) {
    sleep(2); // I used sleep() to simulate processing
    echo '$("#progressbar").progressbar({ value: 25 });';
    }
if (isset($_GET['fifty-percent'])) {
    sleep(2);
    echo '$("#progressbar").progressbar({ value: 50 });';
    }
if (isset($_GET['seventyfive-percent'])) {
    sleep(2);
    echo '$("#progressbar").progressbar({ value: 75 });';
    }
if (isset($_GET['onehundred-percent'])) {
    sleep(2);
    echo '$("#progressbar").progressbar({ value: 100 });';
    }

And below is the function I used to get the progress bar to update its position. A little nuts, I know.

下面是我用来让进度条更新其位置的函数。有点疯狂,我知道。

avail_elem = 0;
function progress_bar() {
    progress_status = $('#progressbar').progressbar('value');
    progress_status_avail = ['twentyfive-percent', 'fifty-percent', 'seventyfive-percent', 'onehundred-percent'];
    if (progress_status != '100') {
        $.ajax({
            url: 'test.php?' + progress_status_avail[avail_elem],
            success: function(msg) {
                eval(msg);
                avail_elem++;
                progress_bar();
                }
            });
        }
    }

If I had to guess, I bet there is a better way... But this is the way it worked for me when I tested it.

如果我不得不猜测,我敢打赌有更好的方法……但这就是我测试它时对我有用的方式。

回答by Andrey Voev

Check this if you use jQuery: http://docs.jquery.com/UI/Progressbar

如果您使用 jQuery,请检查:http: //docs.jquery.com/UI/Progressbar

You can just supply the value of the bar on every AJAX success.

您可以在每次 AJAX 成功时提供 bar 的值。

Otherwise, if you don't use JS Framework see this: http://www.redips.net/javascript/ajax-progress-bar/

否则,如果您不使用 JS 框架,请参阅:http: //www.redips.net/javascript/ajax-progress-bar/

I don't have a way to test it, but it should go like this:

我没有办法测试它,但它应该是这样的:

    var current = 0;
    var total = 0;
    var total_emails = <?php $total_emails ;?>; 

    $.ajax({

      ...
      success: function(data) {
        current++; // Add one to the current number of processed emails
        total = (current/total_emails)*100; // Get the percent of the processed emails
        $("#progressbar").progressbar("value", total); // Add the new value to the progress bar
      }
    });

And make sure that you'll include jQuery along with jQueryUI, and then to add the #progressbar container somewhere on the page.

并确保将 jQuery 与 jQueryUI 一起包含,然后在页面的某处添加 #progressbar 容器。

I may have some errors though ... You will probably have to round the total, especially if you have a lot of emails.

不过,我可能有一些错误......您可能需要对总数进行四舍五入,特别是如果您有很多电子邮件。

回答by capdragon

Use this answered question

使用这个回答的问题

this is how i implemented it:

这就是我实现它的方式:

    var progressTrigger;
    var progressElem = $('span#progressCounter');
    var resultsElem = $('span#results');
    var recordCount = 0;

    $.ajax({
        type: "POST",
        url: "Granules.asmx/Search",
        data: "{wtk: '" + wkt + "', insideOnly: '" + properties.insideOnly + "', satellites: '" + satIds + "', startDate: '" + strDateFrom + "', endDate: '" + strDateTo + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function (xml) {
            Map.LoadKML(xml);
        },
        beforeSend: function (thisXHR) {
            progressElem.html(" Waiting for response from server ...");
            ResultsWindow.LoadingStart();

            progressTrigger = setInterval(function () {
                if (thisXHR.readyState > 2) {
                    var totalBytes = thisXHR.getResponseHeader('Content-length');
                    var dlBytes = thisXHR.responseText.length;
                    (totalBytes > 0) ? progressElem.html("Downloading: " + Math.round((dlBytes / totalBytes) * 100) + "%") : "Downloading: " + progressElem.html(Math.round(dlBytes / 1024) + "K");
                }
            }, 200);


        },
        complete: function () {
            clearInterval(progressTrigger);
            progressElem.html("");
            resultsElem.html(recordCount);
            ResultsWindow.LoadingEnd();
        },
        failure: function (msg) {
            var message = new ControlPanel.Message("<p>There was an error on search.</p><p>" + msg + "</p>", ControlPanel.Message.Type.ERROR);
        }
    });