PHP - Flushing While Loop Data with Ajax

前端 未结 4 1442
温柔的废话
温柔的废话 2020-11-29 09:08

Using PHP, I would like to make a while loop that reads a large file and sends the current line number when requested. Using Ajax, I\'d like to get the cur

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 09:55

    Using:

    • jQuery kill ajax request
    • ignore_user_abort()
    • ob_flush()

    should do all you need in one php thread

    EDIT

    Take a look at nickb's answer, if you're looking for a way how to do this simply it would be following algorithm:

    1. javascript opens process.php via ajax (which will do all the work AND print status reports), you have to look up whether jQuery ajax supports continuous loading
    2. if user decides to stop refreshes you'll kill loading as show in provided link

    In process.php:

    ignore_user_abort(); // Script will finish in background
    while(...){
      echo "Page: $i\n";
      ob_flush();
    }
    

    EDIT 2 requested example (bit of different and ugly, but simple). test_process.php:

    // This script will write numbers from 1 to 100 into file (whatever happens)
    // And sends continuously info to user
    $fp = fopen( '/tmp/output.txt', 'w') or die('Failed to open');
    set_time_limit( 120);
    ignore_user_abort(true);
    
    for( $i = 0; $i < 100; $i++){
        echo "";
        echo str_repeat( ' ', 2048);
        flush();
        ob_flush();
        sleep(1);
        fwrite( $fp, "$i\n");
    }
    
    fclose( $fp);
    

    And main html page:


    After hitting start lines as:

    Line 1
    Line 2
    

    Appeared in the div #foo. When I hit Stop, they stopped appearing but script finished in background and written all 100 numbers into file.

    If you hit Start again script starts to execute from the begging (rewrite file) so would parallel request do.

    For more info on http streaming see this link

提交回复
热议问题