1

尝试在 cakephp 2.1 上使用 JsHelper 创建评论提交表单时遇到了一些麻烦。我想做一个评论系统,就像你在 facebook 上的一样。这是我的代码:

我的应用控制器

class AppController extends Controller {
public $helpers = array('Html', 'Form', 'Js' => array('jquery'));
public $components = array('RequestHandler');
}

我的评论控制器

class CommentsController extends AppController {
public function index() {
    debug($this->RequestHandler);
    $this->set('comments', $this->Comment->find('all'));
    if (!empty($this->request->data)) {
        if ($this->Comment->save($this->request->data)) {
            if ($this->RequestHandler->isAjax()) {
                // Handle Ajax
                $this->render('success', 'ajax');
            }else {
                //$this->Session->setFlash('Comment added');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}

我的评论模型

class Comment extends AppModel {
public $name = 'Comment';

public $validate = array(
    'name' => array(
        'rule' => 'NotEmpty',
        'message' => 'Enter your name.'
        ),
    'email' => array(
        'rule' => 'email',
        'message' => 'Please supply a valid email address.'
        ),
    'content' => array(
        'rule' => 'NotEmpty',
        'message' => 'This field cannot be left blank.'
        )
    );
}

我的索引视图

<table>
<tr>
    <th>Id</th>
    <th>Name</th>
    <th>Email</th>
    <th>Content</th>
</tr>
<?php foreach ($comments as $k => $v): ?>
<tr>
    <td><?php echo $v['Comment']['id']; ?></td>
    <td><?php echo $v['Comment']['name']; ?></td>
    <td><?php echo $v['Comment']['email']; ?></td>
    <td><?php echo $v['Comment']['content']; ?></td>
</tr>
<?php endforeach; ?>
</table>

<div class="page-header">
  <h1>Add a comment</h1>
</div>

<div id="success"></div>
<div>

<?php $data = $this->Js->get('#CommentIndexForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#CommentIndexForm')->event(
      'submit',
      $this->Js->request(
        array('action' => 'save'),
        array(
                'update' => '#success',
                'data' => $data,
                'async' => true,    
                'dataExpression'=>true,
                'method' => 'POST'
            )
        )
    );
 ?>

 <?php 
 echo $this->Form->create('Comment', array('action' => 'index', 'default'=>false));
 echo $this->Form->input('name', array('id' => 'name'));
 echo $this->Form->input('email', array('id' => 'email'));
 echo $this->Form->input('content', array('id' => 'content'));
 echo $this->Form->end(__('Submit'));
 echo $this->Js->writeBuffer();

 ?>
 </div>
  <div id="sending" style='display:none;background-color:lightgreen;'>
  Sending ...
  </div>

有人有想法吗?

4

0 回答 0