In Yii, you can use ajax to execute an action, but this action sometimes requires an error message to pop up. The processing method is as follows:
Basic ideas
Use exception, such
The code is as follows: |
Copy code |
Throw new CHttpException (403, 'You are not authorized to perform this action .'); |
If the exception is CHttpException or YII_DEBUG is true, the error message can be displayed through CErrorHandler: errorAction. In the default yiic generated code, the following code is added to config/main. php:
The code is as follows: |
Copy code |
'Errorhandler' => array ( 'Erroraction' => 'site/error ',), |
However
In Yii 1.1.9 or later, the exceptions thrown by ajax requests are displayed through CApplication: displayException. This makes it impossible to customize the message display mode.
This is the case if the CGridView deletion request throws an exception (YII_DEBUG is true)
Yii 1.1.9 checks that the logic of the ajax request has been removed, so even ajax exceptions are now handled by CErrorHandler: errorAction.
In this way, ajax messages can be DIY.
Example
Use the following code
The code is as follows: |
Copy code |
Public function actionError (){ If ($ error = Yii: app ()-> errorHandler-> error) { If (Yii: app ()-> request-> isAjaxRequest) Echo $ error ['message']; else $ This-> render ('error', $ error );}} |
Later I found a webmaster sharing a piece of code.
The code is as follows: |
Copy code |
Model: Public function rules () { // NOTE: you shocould only define rules for those attributes that // Will receive user inputs. Return array ( Array ('content, author, email ', 'required '), Array ('author, email, url', 'length', 'Max '=> 128 ), Array ('email ', 'Email '), Array ('URL', 'URL '), ); } Controller: If (isset ($ _ POST ['Ajax ']) & $ _ POST ['Ajax'] === 'Comment-form ') { Echo CActiveForm: validate ($ model ); Yii: app ()-> end (); } View: <? Php $ form = $ this-> beginWidget ('cactiveform', array ( 'Id' => 'Post-form', // This is the form id 'Enablesajaxvalidation '=> true, // enter true here. );?> <? Php echo CHtml: errorSummary ($ model);?> <Div class = "row"> <? Php echo $ form-> labelEx ($ model, 'title');?> <? Php echo $ form-> textField ($ model, 'title', array ('size' => 80, 'maxlength' => 128);?> <? Php echo $ form-> error ($ model, 'title');?> </Div> <Div class = "row"> <? Php echo $ form-> labelEx ($ model, 'Content');?> <? Php echo CHtml: activeTextArea ($ model, 'content', array ('rows '=> 10, 'cols' => 70);?> <P class = "hint"> You may use <a target = "_ blank" href = "http://daringfireball.net/projects/markdown/syntax"> Markdown syntax </a>. </p> <? Php echo $ form-> error ($ model, 'Content');?> </Div> <? Php $ this-> endWidget ();?> |
This seems to solve the yii ajax display problem.