阐述在Yii2上实现跳转提示页

序言

为了让用户有更加良好的体验,在操作成功或者失败后,来个提示并跳转页面,我就在Yii2上实现了这一个效果。在写这个跳转提示页的时候,找资料我发现网上关于这方面的中文资料真的很少,大家也都共享下吧!

需求分析

1、用户在操作成功或者失败后,来个提示并跳转页面。
2、使用这种方式$this->success(),$this->error()调用(仿造Yii2自带 $this->render()加载页面的方式)。

效果图

图片描述

样式有点丑,但是功能是好的,要是不喜欢这样式大家可以自行美化一下!

代码分析

1、在控制器的基类Controller.php里边增加两个方法,这么写:

/**
     * 通用成功跳转  
     * @param unknown $url 成功后跳转的URL
     * @param number $sec 自动跳转秒数
     * @return Ambigous <string, string>
     */ 
    public function success($url= [] ,$sec = 3){  
        $url= empty($url)? ['/admin/main']: $url;
        $url= yiihelpersUrl::toRoute($url);
        return $this->renderPartial('../base/msg',['gotoUrl'=>$url,'sec'=>$sec]);
    }
   
    /**
     * 通用错误跳转
     * @param string $msg 错误提示信息
     * @param number $sec
     * @return Ambigous <string, string>
     */
    public function error($msg= '',$sec = 3){
        return $this->renderPartial('../base/msg',['errorMessage'=>$msg,'sec'=>$sec]);
    }

2、在loginviewsbase的下面建立一个命名为msg.php的页面,代码如下:

<?php

/* @var $this yiiwebView */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */

use yiihelpersHtml;

?>

<div class="site-error">

    <div class="alert alert-danger page-none-alert">
        <p>
        <?php if(isset($errorMessage)):?>
            <span class="glyphicon glyphicon-remove-sign text-danger"></span>
            <span class="btn-lg text-danger"><?php echo '操作出错啦!' ?></span>
            <?php echo '<p>'.$errorMessage.'</p>';?>
        <?php else:?>
            <span class="glyphicon glyphicon-ok-sign text-success"></span>
            <span class="btn-lg text-success">恭喜!操作成功!</span>
        <?php endif;?>
    </p>
        
    <p class="text-muted">该页将在3秒后自动跳转!</p>
    <p>
        <?php if(isset($gotoUrl)):?>
            <a href="<?php echo $gotoUrl?>">立即跳转</a>
        <?php else:?>
            <a href="javascript:void(0)" onclick="history.go(-1)">返回上一页</a>
        <?php endif;?>
    </p>
    
    </div>
   <style>
   .page-none-alert{margin: 100px 0 !important;
    text-align: center !important;
    font-size: 30px !important;}
   </style> 

</div>

<script> 
 
<?php if(!isset($gotoUrl)):?> 
   setInterval("history.go(-1);",<?php echo $sec;?>000); 
<?php else:?>
   setInterval("window.location.href='<?php echo  $gotoUrl;?>'",<?php echo $sec;?>000);
<?php endif;?>

</script>

3、完成以上步骤之后就可以在login模块下的控制器里边直接调用了,调用方式如下:
成功的调用方式: return $this->success(['/site/login']);
失败的调用方式: return $this->error('数据修改失败!');

常见问题

1、跳转提示的JS写在如下我注释的地方了,写在那的话就不起作用了,得写在外面才行。

 <?php $this->beginBlock('JUMP_JS')?>
        (function(){
           //跳转提示的JS写在这了。不能写在这,写在这里就不起作用了。
         });
<?php
        $this->endBlock();
        $this->registerJs($this->blocks['JUMP_JS'],yiiwebview::POS_END);?>
        

相关资料

Yii2跳转提示页的写法:http://www.yiifans.com/forum.php?mod=viewthread&tid=11243

本文转载于:猿2048https://www.mk2048.com/blog/blog.php?id=h2ik00aiahj

原文地址:https://www.cnblogs.com/10manongit/p/12942751.html