psy*_*brm 8 javascript php ajax jquery 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();
Run Code Online (Sandbox Code Playgroud)
Ajax加载是这样完成的:
$.get(page, function(formHtml) {
$('#content').html(formHtml);
});
Run Code Online (Sandbox Code Playgroud)
我不得不调用renderPartial processOutput = true,以便输出javascript.小部件生成的JavaScript看起来像这样:
$('#cat-form').yiiactiveform({'validateOnSubmit':true,'attributes':[...]});
Run Code Online (Sandbox Code Playgroud)
我已经将问题追溯到这样一个事实:当$('#cat-form')选择完成时,返回的jQuery对象是空的,即还没有表单.
如何在Yii中为ajax加载的内容正确添加客户端验证?
我很蠢,因为这个而浪费了4个小时:
var slider = $('.slider');
var slide = $('<div class="slide">').html(resp); // facepalm
// few lines later..
slider.append(slide);
Run Code Online (Sandbox Code Playgroud)
因此,当表单仅在临时元素中时,脚本已执行,该元素尚未附加到页面.因此,$('#form')没有找到任何东西.
由于我只是浪费了几个小时寻找解决方案(我觉得这在编程中发生了很多),我现在也可以解释整个事情,以便其他人不必像我一样.:|
$form = $this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>true,
...
Run Code Online (Sandbox Code Playgroud)
public function actionCreate() {
$model=new Model;
$this->performAjaxValidation($model);
...
Run Code Online (Sandbox Code Playgroud)
$outputJs = Yii::app()->request->isAjaxRequest;
$this->renderPartial('_form', array('model'=>new Model), false, $outputJs);
Run Code Online (Sandbox Code Playgroud)
$.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
Run Code Online (Sandbox Code Playgroud)
祝好运.