序言
为了让用户有更加良好的体验,在操作成功或者失败后,来个提示并跳转页面,我就在Yii2上实现了这一个效果。在写这个跳转提示页的时候,找资料我发现网上关于这方面的中文资料真的很少,大家也都共享下吧!
需求分析
1、用户在操作成功或者失败后,来个提示并跳转页面。2、使用这种方式$this->success(),$this->error()调用(仿造Yii2自带 $this->render()加载页面的方式)。
效果图
样式有点丑,但是功能是好的,要是不喜欢这样式大家可以自行美化一下!
代码分析
1、在控制器的基类Controller.php里边增加两个方法,这么写:
1 | public function success( $url = [] , $sec = 3){ $url = empty ( $url )? [ '/admin/main' ]: $url ; $url = /yii/helpers/Url::toRoute( $url ); return $this ->renderPartial( '../base/msg' ,[ 'gotoUrl' => $url , 'sec' => $sec ]); } public function error( $msg = '' , $sec = 3){ return $this ->renderPartial( '../base/msg' ,[ 'errorMessage' => $msg , 'sec' => $sec ]); } |
登录后复制
2、在loginviewsbase的下面建立一个命名为msg.php的页面,代码如下:
1 | <?php use yii/helpers/Html;?><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写在如下我注释的地方了,写在那的话就不起作用了,得写在外面才行。
1 | <?php $this ->beginBlock( 'JUMP_JS' )?> ( function (){
|
登录后复制