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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler