我试图弄清楚为什么我的重置"重启"按钮不能正常工作,因为增加的猜测仍在上升。如果有人放弃,我还需要添加一个显示正确数字的按钮。感谢先前警告的帮助,这些是我坚持的两个部分。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guessing Game</title>
</head>
<body>
<center><form action="game.php" method="POST">
Guess a number 1-100:<input type="text" name="userGuess"/>
<input type="submit" value="Guess"/>
<center><form action="game.php">
<input type="reset" value="Restart"/>
</form></center>
</body>
</html>
<?php
session_start();
$_SESSION['randNum'] = isset($_SESSION['randNum']) ? $_SESSION['randNum'] : rand(0, 100);
$_SESSION['guesses'] = isset($_SESSION['guesses']) ? $_SESSION['guesses'] : 0;
$randNum = $_SESSION['randNum'];
$userGuess = $_POST['userGuess'];
$userGuess = filter_input(INPUT_POST, "userGuess");
if (isset($randNum)) {
if ($userGuess<$randNum) {
echo "<center>You guessed too low!</center>";
$_SESSION['guesses']++;
echo $_SESSION['guesses'];
}
if ($userGuess>$randNum) {
echo "<center>You guessed too high!</center>";
$_SESSION['guesses']++;
echo $_SESSION['guesses'];
}
if ($userGuess==$randNum) {
echo "<center>Congratulations You're right!!!</center>";
unset($_SESSION["randNum"], $_SESSION['guesses']);
}
if ($userGuess>100 || $userGuess<0) {
echo "<center>Please enter a number betweeen 1 and 100!</center>";
}
}
else {
echo "Please enter a number between 1 and 100";
}
?>
答案 0 :(得分:0)
当您第一次访问该页面时,没有POST数据;这几乎只是一个正常的请求。但是,当您提交表单时,POST数据会随请求一起发送,然后$_POST
包含userGuess
。
只需在代码周围添加if (isset($_POST['userGuess']))
即可解决问题:
if (isset($_POST['userGuess'])) {
$userGuess = $_POST['userGuess'];
// ...
答案 1 :(得分:0)
为什么不使用
if (filter_input(INPUT_POST, "userGuess") != null)
{
}
或
$userGuess = filter_input(INPUT_POST, "userGuess");
这会将$ userGuess设置为null,而不是未定义;
<强>更新强>
你的计数器是用PHP(后端)设置的,你不能使用重置按钮重置它们而不是重新加载页面。
结果按钮的答案很简单。 创建按钮
<input type="button" value="Answer" onclick="Alert('<?php echo $randNum; ?>')" />
其余的,做一点研究......