阐述在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= \yii\helpers\Url::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 yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
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写在如下我注释的地方了,写在那的话就不起作用了,得写在外面才行。
<?php $this->beginBlock('JUMP_JS')?>
(function(){
//跳转提示的JS写在这了。不能写在这,写在这里就不起作用了。
});
<?php
$this->endBlock();
$this->registerJs($this->blocks['JUMP_JS'],\yii\web\view::POS_END);?>
相关资料
Yii2跳转提示页的写法:http://www.yiifans.com/forum.php?mod=viewthread&tid=11243
本文转载于:猿2048https://www.mk2048.com/blog/blog.php?id=h2ik00aiahj
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!