search
HomeBackend DevelopmentPHP TutorialYii使用ajax验证显示错误messagebox的解决方法_PHP

本文实例讲述了Yii使用ajax验证显示错误messagebox的解决方法。分享给大家供大家参考。具体方法如下:

yii 自带了ajax 表单验证 这个可能有些朋友不知道了,但我今天在使用yii 自带的ajax 表单验证 时碰到一些问题,下面我来整理例子与大家参考一下。

在Yii中,可以利用ajax执行一个action,但是这个action有时候会有弹出错误讯息的需求,这时候的处理方式如下

基本思想

利用exception,比如:

代码如下:

throw new CHttpException(403, 'You are not authorized to perform this action.');

如果这个异常是 CHttpException 或者 YII_DEBUG 为 true的时候,错误消息可以通过CErrorHandler::errorAction来显示。在yiic默认生成的代码中,就是通过在 config/main.php 中加入如下代码来实现的

代码如下:

'errorHandler' => array(
    'errorAction' => 'site/error',),

但是在Yii  1.1.9 以上,ajax请求抛出的exceptions是通过CApplication::displayException()来显示的。这使得我们无法定制消息的显示方式。

CGridView 删除请求抛出异常的话就是这个样子,(YII_DEBUG 为 true )

Yii 1.1.9 检查ajax请求的逻辑被移除了,所以现在即便是ajax的异常也是通过CErrorHandler::errorAction处理的。

这样ajax的消息就可以DIY了。

示例

通过如下代码

代码如下:

public function actionError(){
    if($error=Yii::app()->errorHandler->error)
    {
        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
 else
            $this->render('error', $error);
    }
}

后来又发现一个站长分享了一段代码

model:

代码如下:

public function rules()
{
        // NOTE: you should 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:

代码如下:

beginWidget('CActiveForm',array(
    'id'=>'post-form',                      //这是表单id
    'enableAjaxValidation'=>true,      //这里一定写 true
)); ?>
   

   


         echo $form->labelEx($model,'title');
 ?>
        textField($model,'title',array('size'=>80,'maxlength'=>128));
 ?>
         echo $form->error($model,'title');
 ?>
   

   


         echo $form->labelEx($model,'content');
 ?>
         echo CHtml::activeTextArea($model,'content',array('rows'=>10, 'cols'=>70));
 ?>
       

You may use Markdown syntax.


         echo $form->error($model,'content');
 ?>
   

 
$this->endWidget();
?>

这样好像很好的解决了yii ajax显示问题。

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use