我需要在PHP代码中成功匹配时创建一个随机消息,但我不确定如何使用JavaScript完成此操作。在我的代码中,PHP从文件中提取用户名和密码,然后检查用户输入的用户名和密码是否匹配。如果是这样,他们获得访问权限,并且表单消失以显示一条消息(我正在试图弄清楚如何做到这一点)。如果没有,则拒绝访问,并保留表单以等待他们再次尝试。
我已经尝试将代码更改为onload
,onclick
和addEventListener
,但没有任何显示。我还尝试将HTML标签更改为element
和p
。这是不可能的吗?我不认为onclick
会很好,因为提交按钮被点击了,但我试了一下,看看我是否能让它工作。
PHP
//NO ERRORS AVAILABLE AND THE BUTTON HAS BEEN PUSHED
if (!$error && isset($_POST['submit']))
{
echo '<div class = "output">
<h1 class = "success">'.$msg.'</h1>
<p id="welcomeDisplay" onload="newWelcome()"></p>
<p id="welcomemsg"></p>
</div>';
}
JavaScript
var welcome =
[
"Success feels so good!",
"You made it!",
"You are worthy!",
"Open Sesame",
"Welcome to the dark side!",
"Hola!",
"So glad you are back!",
"Hello, sunshine!",
"Howdy, partner",
"what's kickin', little chicken?",
"Peek-a-boo!",
"Ahoy, matey!",
"Aloha!",
"Bonjour!",
"Hallo!",
"Ciao!",
"Konnichiwa!"
];
/*-----------------------------------------------------------------*/
function newWelcome()
{
var randomNumber = Math.floor(Math.random() * (welcome.length));
document.getElementById('welcomemsg').innerHTML = welcome[randomNumber];
}
如果php脚本是在根级别,你可能会尝试添加这样的东西到你的scripts.js
文件,但你可能需要调整它,以说明在url或路径中没有脚本名称,如果它是在子文件夹
document.addEventListener('DOMContentLoaded',()=>{
let arr=location.href.split('/');
let page=arr.pop();
let path=arr.pop();
/*
You might need to use the path variable too!
*/
if( page=='index.php' ){
const welcome=[
"Success feels so good!",
"You made it!",
"You are worthy!",
"Open Sesame",
"Welcome to the dark side!",
"Hola!",
"So glad you are back!",
"Hello, sunshine!",
"Howdy, partner",
"what's kickin', little chicken?",
"Peek-a-boo!",
"Ahoy, matey!",
"Aloha!",
"Bonjour!",
"Hallo!",
"Ciao!",
"Konnichiwa!"
];
let msg=welcome[Math.floor(Math.random() * (welcome.length))];
document.getElementById('welcomemsg').innerHTML=msg
}
})