将请求CakePHP函数中的数据传递回jQuery

时间:2011-11-16 16:55:02

标签: ajax cakephp jquery

我正在尝试使用jQuery-Event .blur()构建Ajax-Validations 我已将字段名称设置为输入字段的id以标识它们,并通过ajax-request向Controller提供所需的数据验证。到目前为止,这么好,我可以从验证开始,但问题是: 如果出现错误 - 如何将Errormessage发送回jQuery,以便我可以执行另一个ajax-request来发送它?

感谢所有人的帮助,希望能来。

到目前为止,这是JQuery-Script:

$('.registration').blur(function(){
  var id =  $(this).attr('id');
  var value = $(this).val();
  var dataString = 'id=' + id +'&value=' + value;

  $.ajax({
   type: "POST",
   url: "users/validate",
   data: dataString,
   cache: false,

   success: function(){  }
  });
});

2 个答案:

答案 0 :(得分:0)

验证它的页面应该打印带有结果的JSON;像这样的东西

查看:

<?php
     echo $javascript->object($result);
?>

<?php
     echo json_encode($result);
?>

控制器

假设您进行了验证,并且如果evcrything正常则使用$ validate变量

$this->layout='json_cont';
//do your validations here
if ($validate)
     $result = array(
          'result' => 1,
          'error' => null
      );
else 
     $result = array(
          'result' => 0,
          'error' => 'error validating'
      );
$this->set('result', '$result);

您还需要布局json_cont

<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: text/x-json');
echo $content_for_layout;
?>

最后你只需要改变你的ajax功能就像这样

$.ajax({
   type: "POST",
   url: "users/validate",
   data: dataString,
   cache: false,
dataType: "json",
dataFilter: function(data, type) { 
    return data;
    },
success: function(data) {
    if (data != null && data.result == 0) {
        alert(data.error);
    }
    else {
        //do here something that accepts your validation, like a js function to give some info to the user or something
    }
},
error: function(data) { 
    try {                           
        alert('error doing the validation');
    } catch (e) { }
}
});

我想我不会遗漏任何东西,希望这可以帮助你:D

答案 1 :(得分:0)

我建议使用Cake的 RequestHandler 组件来检测ajax请求。然后,您将布局设置为false,以便仅返回视图。

然后使用您首选的方法正常执行验证。

最后,如果验证失败,您可以返回一个'json'视图,在该视图中呈现返回的验证错误。

这是一个仅涵盖ajax请求和失败验证的基本示例:

用户控制器:

  /**
   * use the RequestHandler component
   */
  public $components = array('RequestHandler');

  /**
   * validate action
   */
  public function validate()
  {
    /**
     * check if it's an ajax request
     */
    if ($this->RequestHandler->isAjax()) {

      $this->layout = false;

      /**
       * set incoming data in the user models data property
       */
      $this->User->set($this->data);

      if (!$this->User->validates()) {

        /**
         * return the validation errors and use a view than renders the json
         */
        $this->set('errors', $this->User->invalidFields());
        $this->render('/users/json/validate');

      }
    }
  }

用户/ JSON / validate.ctp

<?php echo $javascript->object($errors); ?>