javascript - Yii 客户端验证不适用于 ajax 加载的表单

标签 javascript php jquery ajax yii

当我用正常请求(非 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 调用 renderPartial,以便它输出 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 中的 enableAjaxValidation

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

2。 ModelController.php 中的 performAjaxValidation

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

祝你好运。

关于javascript - Yii 客户端验证不适用于 ajax 加载的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388225/

相关文章:

javascript - 我的列表的下一个和上一个按钮不起作用

javascript - if语句的逻辑只达到9/10

php-如何使用ajax发布值?

php - 如何从 PHP mySQL 查询中回显图像数组?

javascript - 如何在 if 语句中禁用/伪造 .remove() ?

javascript - jquery fancybox2 - 如何使覆盖层上的内容不可点击

Javascript 监听 DOM 中的多个事件

php - 用 Preg_Replace 替换撇号时出现问题

jquery - 获取图像的原始宽度和高度

javascript - 如何使用通过 AJAX 加载的内容中的 javascript?