简体   繁体   中英

PHP print string in while loop

I have a function in file do.php like this:

<?php
    if(isset($POST['submit']))
    {
        for($i=0;$i=10;$i++)
        {   
            $reponse = array(
                'content' = > "This is an example - process #" . $i;
            );
            echo json_encode($response);
            sleep(1); // sleep one second each loop
        }
    }
?>

and I have some short JQUERY codes use ajax to post data...

<button onclick="post()">Submit</button>
function post()
{
    $.ajax({
        type: "POST",
        url: "do.php",
        data: data,
        success: function (data){
            var json = jQuery.parseJSON(data);
            $('#result').html(json.content);
        }
    });
}

and this is the output...

This is an example - process #1
This is an example - process #2
This is an example - process #3
....

When I click on Submit button, I can see a request on firebug run 10 seconds to finish and show the result. Now I want each result showed line by line when it finish in the while loop. I can build a websocket system but this system take very much my times and to big system, I just need a simple way to do this if possible.

I still try to save output in to txt file and use JQUERY read it every 500ms but this way take too much request and it doesn't work well.

What are you trying to achieve ? From what I understand you try to execute several processes in SERVER side, and you want, from CLIENT side, to query their status(which process is still running/finished...)
If so, IMO you can execute those processes(using fork() or whatever), and let the parent process to return a list of unique token identifier for each process, to your AJAX request.
Now for every 500ms, using setInterval() , query the of the tokens your received.

Hope it help a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM