weixin_33709219 2015-11-04 11:39 采纳率: 0%
浏览 16

在ajax中加载元素

I am loading some comments in via ajax, default is 5 onload then the user can request more if they want.

This is more a question of good practice.

Where is the best place to build to html elements that will be displayed on the page.

Should I build them up in the javascript file then display them?

I am using Yii framework if this is any help.

  • 写回答

1条回答 默认 最新

  • from.. 2015-11-05 03:35
    关注

    There are certainly a number of ways you can achieve this. I've faced a similar issue before (also related to a Comments system) and what I did was to create a custom Widget and simply load it in the controller. Widgets can have view files which will be loaded upon request and you can simply inject the output into a specific place in your page. Here's what I have in my code:

    /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,
        ));
    }
    

    /protected/views/comments.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>
    
    评论

报告相同问题?