2011-04-16 20:41:41 0 评论 Yii 1.0 Boy.Lee

在Yii 1.0 框架中使用Ajax验证码

{Model}

class Lab extends CFormModel{
    public $verifyCode ;
    
    public function rules()
    {
        return array(
            array('verifyCode','captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
        );
    }
}

 

{Controller}

public function actions()
{
    return array(
        'captcha'=>array(
            'class'=>'CCaptchaAction',
            'backColor'=>0xFFFFFF,
            'minLength'=>4,
            'maxLength'=>6,
            'transparent'=>true,
            'testLimit'=>20,
    ),
    );
}
//Captcha Lab
public function actionCaptchaTest()
{
    $model = new Lab();
        
    // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='captcha-form')
        {
//            $filePath = Yii::app()->basePath.'/../DBox/tmp.txt';
//            $fp = fopen($filePath, 'w');
//            fwrite($fp, serialize($_POST));
//            
//            fclose($fp);
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    
        if (isset($_POST['Lab'])){
        $model->attributes = $_POST['Lab'];
        $model->validate();
    }
    $this->render('captchatest', array('mCaptcha'=>$model));
}

 

 

{View}

$form = $this->beginWidget('CActiveForm', array(
    'id'=>'captcha-form',
    'enableAjaxValidation'=>true,
    'focus'=>array($mCaptcha,'verifyCode'),
));

$this->widget('CCaptcha', array('clickableImage'=>true,'showRefreshButton'=>false));
echo $form->textField($mCaptcha,'verifyCode');

echo $form->error($mCaptcha,'verifyCode',array(
    'validateOnType'=>true,
    'hideErrorMessage'=>true,
    'afterValidateAttribute'=>'js:function(form, attribute, data, hasError){
    	console.log(form);//put object to chrome for look only
    	console.log(attribute);//put object to chrome for look only
    	console.info(data);//put object to chrome for look only
    	console.log(hasError);//put object to chrome for look only
    	
    	//alert(data[attribute.inputID]);
    	
    	if(hasError){
    		$("#lee").val(data[attribute.inputID]);
    	}else{
    		$("#lee").val("");
    	}
    }',
));

echo CHtml::textField('lee');
$this->endWidget();


{Boy Say}

Ajax异步获取Model里定义的rules返回的结果,然后放到自定义的那个文本框里,这个部分的定义代码都在clientOptions 那边有介绍,推荐读一下,很强力。