2015-11-04 110 views
0

我正在通過ajax加載一些註釋,默認值是5 onload,那麼用戶可以請求更多,如果他們想。在ajax中加載元素

這是更好的實踐問題。

哪裏是最好的地方建立html元素,將顯示在頁面上。

我應該在javascript文件中構建它們然後顯示它們嗎?

我正在使用Yii框架如果這是任何幫助。

+0

只需將javascript中創建的html附加到頁面中的圖層 –

回答

0

確實有很多方法可以實現這一點。我以前遇到類似的問題(也與評論系統有關),我所做的是創建一個自定義的Widget,並將其加載到控制器中。小部件可以具有查看文件,這些文件將根據請求加載,您可以簡單地將輸出插入頁面中的特定位置。 這是我在我的代碼:

/protected/widgets/LoadComments.php

class LoadComments extends CWidget { 

    public $offset; 
    public $limit; 
    public $comments; 

    public function run() { 
     //(some offset and limit logic here) 
     $criteria = new CDbCriteria(); 
     // some criteria definitions here (...) 

     $this->comments = Comment::model()->findAll($criteria); 

     $this->render('listComments', array()); 
    } 
} 

/protected/controllers/CommentController.php

public function actionListComments($offset = 0, $limit = 10) { 
    $this->widget("application.widgets.LoadComments", array(
     "offset" => $offset, 
     "limit" => $limit, 
    )); 
} 

/保護/視圖/評論。 php

<div id="comments"></div> 
<script> 
    $(document).ready(function(){ 
     $.ajax({ 
      type: 'GET', 
      data: { offset : 0, limit : 10}, 
      url: '<?php echo Yii::app()->createUrl('/comment/listComments');?>', 
      success: function(data) { 
       $('#comments').html(data); 
      } 
     }); 
    }); 
</script>