php - CakePHP ajax 表单更新复制页面

标签 php ajax cakephp cakephp-2.1

我的网站上有一个使用 Js 助手的基本 ajax 表单,它工作正常,但是当出现验证错误时,更新回调会复制我的成功 div 中的整个页面。

成功部分:

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

提交按钮:

echo $this->Js->submit('Send', array(
    'before'=>$this->Js->get('#sending')->effect('fadeIn'),
    'success'=>$this->Js->get('#sending')->effect('fadeOut'),
    'update'=>'#success',
    'class'=>'btn btn-primary'
));

Javascript:

$(document).ready(function(){

    $('#postkey, #gender, #hair, #location, #message').blur(function(){
        $.post(
            '/Cake_ajax/Posts/validate_form',
            { field: $(this).attr('id'), value: $(this).val() }
            //handleNameValidation
        );
    });

});

在我的 Controller 中验证表单函数:

public function validate_form(){
    if($this->RequestHandler->isAjax()){
        $this->request->data['Post'][$this->request['data']['field']] = $this->request['data']['value'];
        $this->Post->set($this->request->data);
        if($this->Post->validates()){
            $this->autorender = FALSE; // don't render a view
            $this->set('error','');
        }else{
          $this->layout ="ajax";
            $this->autoRender = FALSE;
            $error = $this->validateErrors($this->Post);
            $this->set('error',$this->Post->validationErrors[$this->request['data']['field']][0]);  
        }
    }
}

我不知道这些信息是否足够继续,如果我需要发布更多代码,请告诉我。

谢谢。

最佳答案

我刚刚使用您的 zip 文件测试了您的应用程序。

我观察到的是,这不是放在 #success div 中的整个页面,而只是 Posts/add.ctp View 的内容。 所以基本上这意味着 RequestHandler 正确地完成了它的工作,这意味着使用的布局“ajax”布局。 要删除表单之外的任何其他内容,add.ctp 页面不应包含表单之外的任何内容。在您的情况下,Posts/add.ctp 包含导航链接,这就是它们重复的原因。

也就是说,提交按钮当前所做的是获取 Posts/add.ctp View 的内容并将其插入空的 #success div。但是您永远不会删除页面上已有的表单。 您可以做的是更新包含第一个表单的 div 的内容,甚至更新整个 Posts/add.ctp View 的内容。

在您的情况下,只需更新 #content 而不是 #success div 可能会满足您的需求:

echo $this->Js->submit('Send', array(
  'before'=>$this->Js->get('#sending')->effect('fadeIn'),
  'success'=>$this->Js->get('#sending')->effect('fadeOut'),
  'update'=>'#content',
  'class'=>'btn btn-primary',
  'controller'=>'posts',
  'action'=>'add'
));

关于php - CakePHP ajax 表单更新复制页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10343037/

相关文章:

javascript - Vue/Vuex - 两个或多个具有异步调度(ajax)的组件

javascript - 对每个带有 class/id 的 div 使用 ajax

php - Ajax 响应在服务器上是 JSON,而在本地计算机上使用 CakePHP 时是 STRING,为什么?

cakephp - saveAll() 使用 CakePHP 2.3.1 失败

php - 合并具有共享相同项目数的键的数组

php - 我如何排除表字段MYSQL

php - 从多对多表中检索分组

php - 我应该使用 PDO 在自己的数据库类中抛出异常吗?

javascript - 如何使用ajax请求将印地文字体从客户端传递到服务器

mysql - 为什么 count(id) 结果是 3 维数组?