如何从控制器动作到视图获得响应和返回结果


How to get the response and return result from controller action to view

我已经在View中编写了这个脚本。在onblur事件中,我检查了邮件id是否已经退出。为此,我必须将mailId id传递给控制器动作,我想获得返回结果。

$.ajax({
        type: "POST",
        url: "<?php Yii::app()->createAbsoluteUrl("Approval/checkMailid"); ?>",
        data: mailId,
        success: function() {
          return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
public function actionCheckMailid($mailId)
{
   $model = YourModel::model()->findAll('id = :mid', array(':mid'=>$mailId));
   echo json_encdoe($model);
}

只需抛出404页面,ajax错误处理程序就可以捕获它。

public function actionCheckMailid($mailId){
    $exist = Yii::app()->db->createCommand('select count(*) from your_email_table where id_email = :id_email')
                        ->queryScalar(array(
                            'id_email' => $mailId
                        ));
    if($exist > 0){
        echo json_encode(array(
            'success'=>true
        ));
    }else{
        throw new CHttpException('Email can not be found');         
    }                           
}