8

当我使用正常请求(非 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);
});

我不得不用 调用 renderPartial 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')没有找到任何东西。

4

1 回答 1

9

由于我刚刚浪费了几个小时来寻找解决方案(我觉得这在编程中经常发生),我现在不妨解释一下整个事情,这样其他人就不必像我一样结束了。:|

1.在_form.php中启用AjaxValidation

$form = $this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>true,
    ...

2.在ModelController.php中执行AjaxValidation

public function actionCreate() {
    $model=new Model;
    $this->performAjaxValidation($model);
    ...

3.让renderPartial输出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

祝你好运。

于 2013-10-15T20:59:23.140 回答