Yii widget reload via ajax

我是研究僧i 提交于 2020-01-06 02:16:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!