如何在cakephp 2.3中向客户端返回ajax请求响应(数据)

时间:2013-03-06 21:00:42

标签: php jquery ajax cakephp cakephp-2.3

我正在尝试使用cakephp 2.3中的ajax添加到数据库,但是不知道如何设置响应,但是对于用户来说我会使用其他数据

$this->set()

正常请求 视图文件:

        echo $this->Form->create(); echo $this->Form->input('name');
    echo $this->Form->input('email');
    echo $this->Form->input('phone');
    echo $this->Form->input('message');
echo $this->Js->submit('Send Enquiry', array(
    'before' => $this->Js->get('#sending')->effect('fadeIn'),
    'success' => $this->Js->get('#sending')->effect('fadeOut'),
             'update' => '#success',
              'async' => true
               ));echo $this->Form->end();?>

,控制器功能是:

public function add() {
    if ($this->request->is('post')) {
        $this->Contact->create();
        if ($this->Contact->save($this->request->data)) {

            if($this->request->isAjax()){
                $this->autoRender = false;  
                echo 'successful';
                }else{
            $this->Session->setFlash(__('The contact has been saved'));
            $this->redirect(array('action' => 'index'));
                }
        } else {
            $this->Session->setFlash(__('The contact could not be saved. Please, try again.'));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

抱歉,如果我的问题被错误地措辞,但我找到了解决问题的方法 我使用下面的代码片段来获取验证错误。

if($this->request->isAjax()){

        $this->autoRender = false;      
        if($this->Contact->validates()){

        }else{
        $error = implode($this->Contact->validationErrors;
        echo $error;


            }
        }

感谢所有相同的