Skip to content

Instantly share code, notes, and snippets.

@hscstudio
Created February 2, 2016 12:05
Show Gist options
  • Save hscstudio/d256b888eba46c54b297 to your computer and use it in GitHub Desktop.
Save hscstudio/d256b888eba46c54b297 to your computer and use it in GitHub Desktop.
// view index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
?>
<div class="category-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php Pjax::begin(['timeout'=>false,'id'=>'gridview']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
...
],
]); ?>
<?php Pjax::end() ?>
</div>
<?php
$this->registerJs('
var currentData = "";
var source = new EventSource("'.Url::to(['category/check']).'");
source.addEventListener("message", function(event) {
var data = JSON.parse(event.data);
console.log(data.lastId)
if(currentData!=data.lastId){
currentData = data.lastId;
$.pjax({
url:"'.Url::to(['category/index']).'",
container:"#gridview",
timeout:false,
push: false,
}).done(function(data) {
});
}
}, false);
');
// Controller
<?php
namespace app\controllers;
...
class CategoryController extends Controller
{
...
public function actionIndex()
{
$searchModel = new CategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->getSort()->defaultOrder = ['id'=>SORT_DESC];
if(Yii::$app->request->isAjax){
return $this->renderAjax('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
else{
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
public function actionCheck()
{
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//echo "retry: 10000\n"; // Optional. We tell the browser to retry after 10 seconds
$category = Category::find()->select('id')->orderBy('id DESC')->one();
echo = "data: {\"lastId\": \"".$category->id."\"}\n\n";
flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment