如何在cakephp 2.x中的ajax渲染期间传递变量

时间:2014-05-28 02:56:41

标签: php ajax cakephp

我想将一个变量传递给我的ajax渲染函数。像这样的东西

$this->render('tempcomment/'.$id, 'ajax');

我的临时行动是

public function tempcomment($id) {
    $commentdata = $this->Post->Comment->findByPostid($pid);
    $this->set('commentdata', $commentdata);
}

但渲染不起作用。

3 个答案:

答案 0 :(得分:2)

见下文开头:

public function tempcomment($id) {
                        //   ^ ------ ...
    $commentdata = $this->Post->Comment->findByPostid($pid);
                                                 //    ^--- this is different!
    $this->set('commentdata', $commentdata);
}

答案 1 :(得分:0)

render仅用于决定在控制器操作中使用哪个视图来呈现操作。它不会调用动作本身

所以如果你有这样的代码

public function test() {
    $this->set('foo', 12345);
    $this->render('tempcomment', 'ajax');
}

您只是说要使用tempcomment视图呈现test操作,但您并没有告诉蛋糕实际执行tempcomment操作。

所以,如果你想调用你必须自己做的动作

$this->tempcomment($id);
$this->render('tempcomment/'.$id, 'ajax');

让我告诉你,我认为没有任何理由这样做,我认为可能还有其他方法可以做你想要实现的目标。但我猜你知道你在做什么

答案 2 :(得分:0)

试试这个,它是你想要实现的另一个工作:

 public functionc ajax_tempcomment($id){ //just access this action
      $this->redirect('tempcomment/'.$id);
      $this->layout = "ajax";
 }

 public function tempcomment($id) {
     $commentdata = $this->Post->Comment->findByPostid($pid);
     $this->set('commentdata', $commentdata);
 }