我正在尝试创建一个PHP方法/函数/属性,我可以用JS调用它来向用户显示一条消息,例如"无效的用户登录"然后在显示后重置。
到目前为止,我有以下问题 - 问题是当用户进入下一页或重新加载时,他们会再次收到消息,所以我不想将其设置为null;
<script>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage(){
if(!displayErrorMessage.called)
{
var errorMessage = ("<?php echo "ERROR: ".$_SESSION['error'] ?>");
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
function resetErrorMessage()
{
var errorMessage = null;
setTimeout(function()
{
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
答案 0 :(得分:1)
尝试在显示后删除会话变量。
<script>
<?php if(isset($_SESSION['error'])) { ?>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage(){
if(!displayErrorMessage.called) {
var errorMessage = ('<?php echo "ERROR: ".$_SESSION['error']; ?>');
// Here is where you remove the error so it won't persist to the
// next pages when user continues to navigate through
<?php if(isset($_SESSION['error'])) unset($_SESSION['error']); ?>
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
<?php } ?>
function resetErrorMessage() {
var errorMessage = null;
setTimeout(function(){
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
答案 1 :(得分:0)
试试这个:
<?php if( isset($_SESSION['error']) ) : ?>
<script>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage()
{
if(!displayErrorMessage.called)
{
var errorMessage = ("<?php echo "ERROR: ".$_SESSION['error'] ?>");
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
function resetErrorMessage()
{
var errorMessage = null;
setTimeout(function() {
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
<?php endif; ?>
<?php
unset($_SESSION['error']);
?>