我的网站上有一个使用 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/