如何在 Yii 中重构 AJAX 进程

How to refactor an AJAX process in Yii

本文关键字:重构 AJAX 进程 Yii      更新时间:2023-09-26

我需要重构或设计:)方面的帮助。我做了我的网络应用程序,它运行良好。但我仍然不能很好地理解 Yii 中的 Ajax 过程。例如,当我使用 $.fn.yiiGridView.update() 方法时,我看到的是 all 网页的返回,而不仅仅是 CGridView 的内容。这对我来说很有趣。

但是现在:在索引视图中,我使用CGridView,但没有寻呼机!这是一个简单的投注游戏网络应用程序。在索引处.php我在页面上只查看 10 个投注/结果,10 秒后,我查看下一个 10 个投注/结果,并在 10 秒:)后再次查看下一个 10 个结果/投注,使用 JavaScript。

简单的过程是这样的:

  1. actionIndex() 被调用,它呈现索引.php(索引.php包含设计的JS代码,但不包含CGridView,其中网络应用查看结果)
  2. 索引.php呈现_ajaxIndex.php文件内容。
  3. JS代码计算接下来的10个结果,该结果必须在网页上查看。
  4. actionAjaxIndex() 被调用。这给了_ajaxIndex.php重复的新鲜内容 3.再。
  5. JS代码再次计算接下来的10个资源...

注意:虽然管理员 在管理网页上插入结果,Web 应用程序必须显示 临时结果。这就是为什么我需要刷新摘要和 在_ajaxIndex.php中舍入 JS 变量

控制器

/**
     * Lists all models.
     */
public function actionIndex() {
    Yii::app()->language='hu';
    $model = new Result('search');
    $model->unsetAttributes();
    if (isset($_GET['Result']))
        $model->attributes = $_GET['Result'];
    if (isset($_POST['offset']) && $_POST['offset'] >= 0)
        $model->offset = $_POST['offset'];  
    $summary = Result::getCountSavedResults();
    $model->isLimited = true;
    $this->layout='projector'; 
    $this->render('index', array('model' => $model, 'summary'=>$summary));
    //$this->actionAjaxIndex();
}
/**
 * List all models by Ajax request.
 */    
public function actionAjaxIndex() {
    Yii::app()->language='hu';
    $model = new Result('search');
    $model->unsetAttributes();  // clear any default values
    if (isset($_GET['Result']))
        $model->attributes = $_GET['Result'];
    if (isset($_POST['offset']) && $_POST['offset'] >= 0)
        $model->offset = $_POST['offset'];  
    $summary = Result::getCountSavedResults();
    $model->isLimited = true;
    $this->renderPartial('_ajaxIndex', array('model' => $model, 'summary'=>$summary));
}

我想在 actionIndex() 中重复终止此代码。但我不知道我该怎么做...我试图调用动作AjaxIndex等。但是在我调用actionAjaxIndex之前,我从Yii那里得到了PHP错误。(摘要变量不存在等)

视图 - 索引.php

<!--<h1><?php echo Yii::t('strings','Results'); ?></h1>-->
<?php 
    echo CHtml::image(Yii::app()->request->baseUrl.'/images/toplista.jpg', "Fogadás");
?>
<script type="text/javascript">
    // Initialize the variables for calculating
    var summary = <?php echo $summary ?>; // get all stored results
    var timeout = 10 * 1000; // in Milliseconds -> multiply with 1000 to use seconds
    var current = 0;
    var turn = 0;
    var rounds = Math.floor(summary / 10);
</script>
<?php $this->renderPartial('_ajaxIndex', array('model'=>$model, 'summary'=>$summary)); ?>
<script type="text/javascript">
    // Refresh the CGridView's content in _ajaxIndex.php
    window.setInterval("refresh()", timeout);
    // Get the offset to the search() to set the criteria
    // Increase turn.
    function counter(){
        turn += 1;
        if(turn > rounds){
            turn = 0;
        }
        return turn *10;
    }
    function refresh() {       
        <?php
        echo CHtml::ajax(array(
                'url'=> CController::createUrl("result/ajaxIndex"),
                'type'=>'post',
                'data'=> array('offset'=>'js: counter()'),
                'replace'=> '#ajax-result-grid',
                ))
        ?>
    }
</script>

景观 - _ajaxIndex.php

<?php
/* @var $model Result */
?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'ajax-result-grid',
        'dataProvider'=>$model->search(),       
        'columns'=>array(
                array(
                    'header'=>Yii::t('strings','No.'),
                    'value'=> $model->offset.' + $row+1',
                    'htmlOptions'=>array('style'=>'width:50px;'),
                 ),
                array(
                    'header'=>Yii::t('strings','team_name'),
                    'name'=>'team_id',
                    'value'=>'$data->team->name'
                ),
            array(
                    'header'=>Yii::t('strings','value'),
                    'name'=>'value',
                    'value'=>'$data->value'
                ),
        ),
)); ?>
<script type="text/javascript">
    // This is need while the admins insert the results during this page is run.
    summary = <?php echo $summary ?>;
    rounds = Math.floor(summary / 10);
</script>

是的,我想我不太了解 Yii 中的 Ajax 过程:/。

实际上,您已经向前迈出了一大步,使用相同的模板 - _ajaxIndex.php - 用于 AJAX 调用和初始页面加载。但是,是的,您可以朝这个方向走得更远 - 也可以使用单个操作

在此操作中,应检查该方法的调用方式,无论是否通过 AJAX。 根据结果,您可以呈现整个页面 - 或者只是部分页面。

通常,此检查就像...

if (Yii::app()->request->isAjaxRequest) { ... }

但是这里有一个问题:这个检查取决于自定义的HTTP头HTTP_X_REQUESTED_WITH,许多JS库使用实现自己的AJAX例程。可悲的是,某些代理服务器会删除此标头,因此它可能不可靠。为了 100% 确定,只需在 AJAX 帮助程序中提供另一个参数(最简单的是 ajax ),然后检查这个参数(也)。