当我使用正常请求(非 ajax)打开页面时,一切正常。但是当我使用 ajax 加载该表单时,该表单中的客户端验证不起作用。
表单生成器是经典的 gii 生成的东西:
$form = $this->beginWidget('CActiveForm', array(
'id'=>'cat-form',
'enableAjaxValidation'=>true,
'action' => ...,
'clientOptions'=>array('validateOnSubmit'=>true),
)
);
// - form inputs go here -
$this->endWidget();
Ajax 加载是这样完成的:
$.get(page, function(formHtml) {
$('#content').html(formHtml);
});
我不得不用processOutput = true
调用渲染部分,以便它输出javascript。小部件生成的 javascript 如下所示:
$('#cat-form').yiiactiveform({'validateOnSubmit':true,'attributes':[...]});
我已经将问题追溯到这样一个事实,即当$('#cat-form')
选择完成时,返回的jQuery对象为空,即还没有形式。
如何在 Yii 中正确添加 ajax 加载内容的客户端验证?
我很愚蠢,因此浪费了4个小时:
var slider = $('.slider');
var slide = $('<div class="slide">').html(resp); // facepalm
// few lines later..
slider.append(slide);
因此,当表单仅在临时元素中时,脚本被执行,该元素尚未附加到页面。因此,$('#form')
没有找到任何东西。
由于我刚刚浪费了几个小时寻找解决方案(我觉得这在编程中经常发生),我现在不妨解释一下整个事情,这样其他人就不必像我一样结束。
1. 在_form.php中启用 AjaxValidation
$form = $this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>true,
...
2. 在模型控制器中执行 AjaxValidation .php
public function actionCreate() {
$model=new Model;
$this->performAjaxValidation($model);
...
3. 让渲染部分输出 JavaScript
$outputJs = Yii::app()->request->isAjaxRequest;
$this->renderPartial('_form', array('model'=>new Model), false, $outputJs);
4. 追加 ajax 加载的内容
$.get(url, function(resp) {
$('#content').html(resp);
// !! DO NOT append the html to element that is not yet part of the document
// var slide = $('<div>').html(resp); // WRONG
// $('.slides').append(slide); // WRONG
祝你好运。