使用PRG模式是完成此任务的最佳方式。
index.php
1. 在HTML中创建模态框内容的元素
<div id=modal></div>
2. 为你的 #modal
元素添加样式
#modal {
position: fixed;
display: none;
color: white;
text-align: center;
z-index: 1000;
width: 100%;
height: 80px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: crimson;
line-height: 2;
}
3. 使用jQuery定义函数来显示和隐藏模态框
'use strict'
window.jQuery ?
$.fn.notify = function(interval) {
let el = $(this),
text = el.text(),
modal =()=> {
el.fadeOut(),
clearInterval(timer)
},
timer = setInterval(modal,interval)
!text.match(/\S+/) || el.text('')
.append(`<h3>${text}</h3>`)
.show()
}
: alert('jQuery required.')
4. 将 .notify()
附加到 jQuery 选择器
$(()=>{
$('#modal').notify(1500) // 1500 is the interval in milliseconds
})
5. 将从 PHP 发送的通知插入到 #modal
元素中
<div id=modal>
<?=
@$_SESSION["notify"]; // if this variable is not set, nothing will happen
unset($_SESSION["notify"]);
?>
</div>
6. 执行一个简单的 $_GET
请求
<a href=parse.php?logout>Logout</a>
parse.php
7. 使用 PHP 在 $_SESSION
变量中返回一个值
if (isset($_GET["logout"])) {
$_SESSION["notify"] = "You have been logged out.";
header("Location: index.php");
}
这是一个好的实践。一旦注销请求被发送到PHP,它将通过会话变量重定向到主页并显示结果。PRG模式并不总是需要POST请求。此示例发送GET请求,适用于注销操作。请注意,在文件顶部必须放置session_start();
。