问题
I need to reload a content of my Yii widget via AJAX every XX seconds.
This is my widget code:
class UserOnlineWidget extends CWidget
{
public function init(){
}
public function run(){
$userOnline=User::getOnlineUser();
$this->render("userOnLineWidget", array('userOnline'=>$userOnline));
}
}
And this is the view userOnLineWidget.php:
<div class="userOnline">
<h5>User Online</h5>
<ul>
<?php
foreach($userOnline as $user) {
?>
<li>
<ul>
<li><?php echo CHtml::link($user['username'], array('/site/view/'.$user['id'])); ?></li>
<li><?php echo ($user['online'] != null)? 'online' : 'offline'; ?></li>
</ul>
</li>
<?php
}
?>
</ul>
</div>
How can I do this ? I use Yii 1.1.
回答1:
Here a small example. I hope this help you. Widget which show time from server every second.
//SiteController
public function actionTest()
{
$this->render('my_view'); //just rendering view
}
public function actionContent()
{
$this->widget('time'); //return html of widget. use for ajax
}
//my_view.php
<script src="<?php echo $this->assetsBase ?>/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$.get('/site/content', {}, function(data) {
$('#widget').html(data);
});
}, 1000); //update widget content every second
});
</script>
<div id="widget">
<?php $this->widget('time'); // render widget ?>
</div>
//widget
class Time extends CWidget
{
public function init(){
}
public function run(){
$date = new DateTime();
$this->render("test", array('time'=>$date->format('H:i:s')));
}
}
//view for widget test.php
<p><?= $time ?></p>
来源:https://stackoverflow.com/questions/30625173/yii-widget-reload-via-ajax