在客戶端,你可以
<?php echo CHtml::activeTextField($model, 'text', array(
'placeholder'=>$model->getAttributeLabel('text'),
'class'=>'form-control'
<script> )); ?>
function Validate(field){
var _this = field;
var errorDiv = _this.parent().find('.errors');
var attr = [];
_this.each(function(){
var match = $(this).attr('name').match(/\[(.*?)\]/);
attr.push(match[1]);
})
jQuery.ajax({
type: 'POST',
url: 'url/',
data: 'ajax=keyup&'+_this.serialize()+'&attr='+attr,
cache: false,
processData: false,
success: function(data){
data=JSON.parse(data);
if(data.success){
_this.addClass('green');
errorDiv.html('');
}else{
_this.addClass('red');
errorDiv.html(data[attr][0]);
}
}
});
}
var delay = (function(){
var Timer = 0;
return function(callback, ms){
clearTimeout (Timer);
Timer = setTimeout(callback, ms);
};
})(); //if you want to delay
$('#traveler_info input').keyup(function(){
var _this = $(this);
timeout = setTimeout(function(){
Validate(_this,'Travelers')
},1000)
});
` 在SiteController
public function actionAjaxvalidation($type = null)
{
$model = new Travelers;
if(isset($_POST['Travelers'], $_POST['attr']))
{
/*
* @params Model->value $attr
*
*/
$attr = $_POST['attr'];
$model->$attr = $_POST['Travelers'][$attr];
if($model->validate(array($attr)))
{
echo json_encode(['success'=>true]);
}
else
{
echo json_encode($model->errors);
}
Yii::app()->end();
}
}
可惜我不能沒有黑客Yii框架的核心文件做到這一點。而且我不直接提交表單,但是jQuery表單插件可以。無論如何我解決了另一種方式。 – 2012-02-21 15:57:22