PHP + Mysql插入+ jQuery进度条

时间:2013-12-14 11:53:29

标签: php jquery mysql ajax progress-bar

我在使用查询将当前插入的行显示到mysql时遇到问题。 现在我在index.php中有这个代码:

  $('#nacitatATC').click(function() {
    $.ajax({
            xhr: function() {

                    var xhr = new window.XMLHttpRequest();
                    xhr.addEventListener("progress", function(e){
                        var p = (e.loaded / e.total)*100;
                        var prave = $("#progress").html();
                              $("#progress").html(prave+"<br>"+p);
                    });
                return xhr;

            }
            , type: 'post'
            , cache: false
            , url: "/sql.php"});

      });
  });

并在 sql.php 我有php代码,用for()将数据插入mysql。 $i是当前的插入行,$pocet是总行数。

问题在于使用ajax显示当前插入行。 当ajax完成加载时,上面的代码显示在 div #progress “100”。

我需要显示1%2%3%4%... 99%100%已完成。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我认为php - &gt; flush()正是你要找的。

此示例在我的debian

上的php-apache上运行完美

请参阅ajax-request-progress-percentage-log

PHP方面:

header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo $i . '<br />';
    flush();
    ob_flush();
    sleep(1);
}
echo 'End ...<br />';

站点:&安培;的javascript:

<!doctype html>
<html>
<head>
    <title>Test Flush</title>
    <meta charset="utf-8">
    <script src="./js/jquery-2.0.3.min.js" type="text/javascript"></script>
<body>
<h1>Hello</h1>
<div id="progress">0%</div>

<p>
</p>
<script type="text/javascript">
    $('h1').click(function() {
    $.ajax({
            xhr: function() {

                    var xhr = new window.XMLHttpRequest();
                    xhr.addEventListener("progress", function(e){
                        console.log(e.currentTarget.response);
                        $("#progress").html(e.currentTarget.response);
                    });
                return xhr;

            }
            , type: 'post'
            , cache: false
            , url: "testFlush.php"
        });

    });

</script>
</body>

另请参阅罗杰斯答案 how-to-flush-output-after-each-echo-call 他在apache设置中发现了问题