【问题标题】:Yii framework: get the resultant html from a view in JavaScriptYii 框架:从 JavaScript 中的视图获取生成的 html
【发布时间】:2014-04-01 16:49:16
【问题描述】:

这是一种特殊情况,但我在一个 yii 应用程序中有一个简单的 .php 视图,它根据传递给它的参数显示一些 html。我这样称呼它:

echo $this->renderPartial('/comments/view', array('comment'=>$comment));

我这样做了好几次,因为页面中可能有多个评论。

这很好用,但是,一旦有人发表新评论,我想在页面上动态显示它而不重新加载它。所以这里来了 AJAX 发挥它的魔力,并在完成后调用一个刷新函数,这需要刷新显示 cmets 的 div 的内容:

    function refreshComments()
    {
        var content = $('#users_posts').html();
        var newContent = "<?php $this->renderPartial('/comments/view', array('comment'=>Comments::getLatestComment($model->id))); ?>";
        $('#users_posts').html(newContent + content);
    }

显然,我试图用所需的 html 填充变量 newContent 的部分失败了。这部分工作没有问题:

Comments::getLatestComment($model->id)

因为我能够从数据库中新插入的评论中获取信息。问题是显示在屏幕上,因为我必须用大量的 html 来包装它,这也取决于 getLatestComment 返回的值。视图做得很好,但是,如何从中获取结果并将其填充到 JavaScript 变量中,以便正确更新 div 的 HTML?

或者以这种方式提出的其他建议也非常受欢迎!

【问题讨论】:

  • 您的代码做错了很多事情。同样关于 Ajax 实现,使用 JSON 将数据发送到视图,并使用 Jquery/Mootools 等库将数据附加到视图中。在下面查看@parry 的答案。

标签: javascript php jquery html yii


【解决方案1】:

有几种方法可以实现您想要做的事情。

第一种方法是更正现有代码,如下所示:-

评论控制器:-

public function actionGetLatestComments($id){ //$id variable is the ID of the latest comment on the page
    if(isset($_POST['post_id'])){
        $post_id = $_POST['post_id'];
        $post = Post::model()->findByPk($post_id);
        if($post){
            //check for any new comments here using the $id variable passed
            //echo out all the HTML of new comment(s) here
        }
    }
}

用户视角:-

这方面您需要跟踪您帖子下的所有 cmets,例如前任。

<div id='users_posts'>
    <div id='2'>
        ...comment with ID 2...
    </div>
    <div id='1'>
        ...comment with ID 1...
    </div>
</div>

假设您的最新评论是评论列表中的第一条评论,您可以通过以下 JS 获取它的 ID:-

$('#users_post div').first().attr('id');

在 JS 函数 refreshComments() 中使用此 ID,如下所示:-

function refreshComments(){
    var id = $('#users_post div').last().attr('id');
    $.post('/comments/getLatestComments/'+id, {post_id:POST_ID_HERE}, function(data){
        $('#users_posts').append(data);
    });
}

使用此方法会增加服务器的开销,因为如果有新评论可用,您的服务器将一次又一次地返回整个 HTML。

或者您可以使用 JSON 数据来减少每个请求的开销,如下所示:-

评论控制器:-

//inside the getLatestComments function
echo CJSON::encode(array(/* here array of new comments if available */));

在用户的视图方面:-

//inside refreshComments function 
var id = $('#users_post div').first().attr('id');
$.post('/comments/getLatestComments/'+id, {post_id:POST_ID_HERE}, function(data){
    data = JSON.parse(data);
    $.each(data, function(id, value){
        $('#users_post').append("<div id='"+value.id+"'>"+value.comment+"</div>");
    });
});

这样您就可以使用 JSON 来获取所有最新的 cmets 并提高效率。

我希望这能解决你的问题。

【讨论】:

  • 完美答案!!正是我会给出的! +1
猜你喜欢
  • 1970-01-01
  • 2011-12-26
  • 2014-06-05
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多