PHP - Ajax で while ループデータをフラッシュする 質問する

PHP - Ajax で while ループデータをフラッシュする 質問する

PHPの使用、大きなファイルを読み取り、要求されたときに現在の行番号を送信する while ループを作成したいと思います。Ajaxの使用現在の行数を取得してページに印刷したいと思います。HTMLボタンの使用一度だけ実行され、ajax メソッド

試してみましたが、何らかの理由で、echo str_repeat(' ',1024*64);関数をコメントアウトしない限り何も印刷されません。コメントアウトすると、ループの結果全体が表示されます。

1 行が処理されました。2 行が処理されました。3 行が処理されました。4 行が処理されました。5 行が処理されました。6 行が処理されました。7 行が処理されました。8 行が処理されました。9 行が処理されました。10 行が処理されました。

次のように別々の行に表示するのではなく、1 行で表示します。

1 row(s) processed.
2 row(s) processed.
3 row(s) processed.
4 row(s) processed.
5 row(s) processed.
6 row(s) processed.
7 row(s) processed.
8 row(s) processed.
9 row(s) processed.
10 row(s) processed.

また、JavaScript スレッドを終了する方法もわかりません。つまり、問題は合計 2 つあります。

 1. It's returning the entire While loop object at once instead of each time it loops.
 2. I'm not sure how to terminate the JQuery thread.

何かアイデアはありますか? 以下はこれまでの私のコードです。

msgserv.php

<?php

//Initiate Line Count
$lineCount = 0;

// Set current filename
$file = "test.txt";

// Open the file for reading
$handle = fopen($file, "r");

//Change Execution Time to 8 Hours
ini_set('max_execution_time', 28800);

// Loop through the file until you reach the last line
while (!feof($handle)) {

    // Read a line
    $line = fgets($handle);

    // Increment the counter
    $lineCount++;

    // Javascript for updating the progress bar and information
    echo $lineCount . " row(s) processed.";

    // This is for the buffer achieve the minimum size in order to flush data
    //echo str_repeat(' ',1024*64);

    // Send output to browser immediately
    flush();

    // Sleep one second so we can see the delay
    //usleep(100);
}

// Release the file for access
fclose($handle);

?>

html 翻訳

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" charset="utf-8"></script>

        <style type="text/css" media="screen">
            .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
            .new{ background-color:#3B9957;}
            .error{ background-color:#992E36;}
        </style>

    </head>
    <body>

    <center>
        <fieldset>
            <legend>Count lines in a file</legend>
            <input type="button" value="Start Counting" id="startCounting" />
            <input type="button" value="Stop Counting!" onclick="clearInterval(not-Sure-How-To-Reference-Jquery-Thread);" />
        </fieldset>
    </center>

    <div id="messages">
        <div class="msg old"></div>
    </div>

    <script type="text/javascript" charset="utf-8">
        function addmsg(type, msg){
            /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
            $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
        }

        function waitForMsg(){
            /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
            $.ajax({
                type: "GET",
                url: "msgsrv.php",
                async: true, /* If set to non-async, browser shows page as "Loading.."*/
                cache: false,
                timeout:2880000, /* Timeout in ms set to 8 hours */

                success: function(data){ /* called when request to barge.php completes */
                    addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                    setTimeout(
                    'waitForMsg()', /* Request next message */
                    1000 /* ..after 1 seconds */
                );
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    addmsg("error", textStatus + " (" + errorThrown + ")");
                    setTimeout(
                    'waitForMsg()', /* Try again after.. */
                    "15000"); /* milliseconds (15seconds) */
                },
            });
        };

        $('#startCounting').click(function() {
            waitForMsg();
        });
    </script>

</body>
</html>

テスト.txt

1
2
3
4
5
6
7
8
9
10

ベストアンサー1

PHP と AJAX がどのように相互作用するかについて混乱しています。

AJAX 経由で PHP ページを要求すると、PHP スクリプトの実行が強制的に開始されます。 を使用してflush()内部 PHP バッファをクリアしている場合でも、ファイル全体が読み取られて接続が閉じられるまで、AJAX 呼び出しは終了しません (つまり、応答ハンドラは呼び出されません)。

あなたが求めているものを実現するには、次のような並列プロセス フローが必要になると思います。

  1. 最初の AJAX ポストは、ファイルの読み取りを開始するためのリクエストを送信します。このスクリプトは、一意の ID を生成し、それをブラウザーに送り返し、実際にファイルの読み取りを行うスレッドを生成して終了します。
  2. 後続のすべての AJAX リクエストは、ファイル読み取りの状態を確認する別の PHP スクリプトに送られます。この新しい PHP スクリプトは、#1 で生成された一意の ID に基づいて、ファイル読み取りの現在の状態を送信し、終了します。

このプロセス間通信は、$_SESSION変数を介して、またはデータベースにデータを保存することによって実現できます。いずれの場合も、現在の順次実装ではなく並列実装が必要です。そうしないと、引き続きステータス全体を一度に取得することになります。

おすすめ記事