0

我正在尝试使用在 CakePHP 2.1 中为联系表单工作的 Ajax 和 jQuery 验证错误。在名称字段模糊时,调用 js 函数:

$(document).ready(function(){

$('#name').blur(function(){
    $.post(
        '/Cake_ajax/Contacts/validate_form',
        { field: $(this).attr('id'), value: $(this).val() },
        handleNameValidation
    );
});

function handleNameValidation(error){
    if(error.length > 0){
        if($('#name-notEmpty').length == 0){
            $('#name').after($('<div id="name-notEmpty" class="error-message">' + error + '</div>'));
        }
    }else{
        $('#name-notEmpty').remove();
    }
}
});

javascript 在我的控制器中调用 validate_form 函数:

public function validate_form(){
        if($this->RequestHandler->isAjax()){
            $this->request->data['Contact'][$this->request->params['form']['field']] = $this->request->params['form']['value'];
            $this->Contact->set($this->request->data);
            if($this->Contact->validates()){
                $this->autorender = FALSE; // don't render a view
            }else{
                $error = $this->validateErrors($this->Contact);
                $this->set('error', $error[$this->request->params['form']['field']]);
            }
        }
    }

在我看来,当错误被调用时,我遇到了几个错误:

Undefined index: form [APP\Controller\ContactsController.php
Undefined index: form [APP\Controller\ContactsController.php

我束手无策,而且我对 CakePHP 还很陌生。任何帮助将不胜感激。

4

3 回答 3

2

尝试$this->request->params['field']代替$this->request->params['form']['field'].

或者在你检查到之后isAjax(),尝试对 var_dump 进行操作$this->request->params。根据您得到的错误,表单索引不存在于$this->request->params.

于 2012-04-19T23:50:05.350 回答
2

在您的控制器中,您应该有如下内容。Cake 2.0 替换了 RequestHandlerComponent 和 Controller 中的许多特性。它还将所有地方的 $this->params 数组和旧的 $this->data 替换为 $this->request->data,类似的东西。您可以访问迁移指南

    public function validate_form(){
        if($this->RequestHandler->isAjax()){
           $this->request->data['Contact'][$this->request['form']['field']] = $this->request['form']['value'];
           $this->Contact->set($this->request->data);
           if($this->Contact->validates()){
              $this->autorender = FALSE; // don't render a view
           }else{
             $error = $this->validateErrors($this->Contact);
             // didn't validate logic
             $this->set('error',$this->Contact->validationErrors[$this->request['data']['field']][0]);
          }
       }
    }
于 2012-04-20T10:33:42.433 回答
0

如果您想在使用标准表单和 Cake FormHelper 时模拟 POST,您也可以简单地命名发布的参数,就像 FormHelper 命名输入字段一样。

$j.post(
    '/Cake_ajax/Contacts/validate_form',
    { "data[Contact][" + $(this).attr('id') + "]": $(this).val() },
    handleNameValidation
);

这会自动填充$this->request->data['Contact']['name'],你可以评论这一行:

//$this->request->data['Contact'][$this->request->params['form']['field']] = $this->request->params['form']['value'];
于 2012-04-20T07:34:59.670 回答