【问题标题】:Dynamically update progressbar yiiframework动态更新进度条 yiiframework
【发布时间】:2014-11-16 16:14:05
【问题描述】:

他在那儿!

我有计算百分比的函数,这些百分比是基于时间的。有一个开始时间(例如 15:00)和一个结束时间(例如 15:05)。如果我在 15:02 调用这个函数,结果将是 40%。

public function getBuildPercentage() {
    $currentTime = strtotime(date('Y-m-d H:i:s')); //50
    $boughtTime = strtotime($this->boughtTime); 
    $finishTime = strtotime($this->finishTime); //100

    $first = $currentTime - $boughtTime; 
    $second = $finishTime - $boughtTime; 

    $percentage =   round(($first / $second) * 100);    

    // if the percentage is higher than 100 -> item is finished
    if($percentage >= 100)
        $this->setToFinished($this->id); 

    return $percentage; 
}

我使用引导进度条小部件显示此百分比,如下所示:

<?php
    $this->widget(
        'bootstrap.widgets.TbProgress',
        array(
            'type' => 'success', 
            'percent' => $item->getBuildPercentage(),
            'htmlOptions' => array(
                'data-toggle' => 'tooltip',
                'title' => 'Approximately ...to go.'
                )                                
            )
        )
?>

目前,用户必须刷新页面才能看到百分比的确切值和正确的进度条。

如果进度条能够动态更新(因此无需刷新),那就太酷了。

最好的方法是什么?阿贾克斯? (我没有这方面的经验,所以如果你也能举个例子,那就太好了!)

非常感谢您的时间和精力。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    首先,对于 AJAX,您应该可以通过请求访问您的函数,因此将此代码放在您的控制器中:

    public function actionPercentage($id) {
    if (Yii::app()->request->isAjaxRequest) {
       $item = YourModelName::model()->findByPk($id); //obtain instance of object containing your function
       echo $item->getBuildPercentage(); //to return value in ajax, simply echo it   
    }
    }
    

    然后,在您看来,您可以注册每秒向服务器发送请求以获取当前百分比的脚本:

    Yii::app()->clientScript->registerCoreScript('jquery');
    Yii::app()->clientScript->registerScript('ajax-percentage','
       var interval = 1000;
       setInterval(function() { $.ajax(
            type: "GET",
            url: '.Yii::app()->createUrl('yourController/percentage', array('id'=>$item->id)).',
            success: function (percents) {
                // you have got your percents, so you can now assign it to progressbar value here
            }
     )}, interval);
    ');
    

    如果您对 Bootstrap 小部件有任何问题,我还建议您使用 JQuery UI Progressbar

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 2023-03-14
      • 1970-01-01
      • 2013-03-08
      • 2020-11-05
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多