LoginSignup
11
10

More than 5 years have passed since last update.

fuelphpで重たい処理の進捗をajaxで簡易的にゲットする

Last updated at Posted at 2015-11-20

重たい処理の進捗を把握したい時がたまにある
進捗をセッションで管理して簡易的にゲットしてみる

PHP側

foo.php
<?php

use Fuel\Core\Session;

class Controller_Foo extends Controller_Rest
{
    // 重たいアクション
    public function get_hevy()
    {
        // パラメータ初期化
        $progress = 0;          // 進捗
        Session::delete('progress');    // クリアしとく

        // クソ重たい処理(1秒間で10%進む)
        for ($i = 0; $i < 10; $i++) 
        {
            $progress += 10;
            Session::set('progress', $progress );   // 進捗セット
            Session::write();               // スクリプト終了前に書き込み←重要
            sleep(1);
        }

        $this->response(['str' => 'complete!']);
    }

    // 進捗取得アクション
    public function get_progress()
    {
        $this->response(['progress' => Session::get('progress', 0)]);
    }
}

javascript側

hoge.js
$(function(){

    // 重い処理を呼び出す
    $.get('foo/hevy',function(data){

        // 結果出力
        console.log(data.str);

    }, "json");

    // 進捗を1秒間隔で呼び出す
    progressInterval=setInterval(function(){

        $.get('foo/progress',function(data){
            // 進捗出力
            console.log(data.progress);// 進捗出力

            // 100になったら終わり
            if(data.progress >= 100) clearInterval(progressInterval);
        }, "json");

    } , 1000);
});
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10