开发思路:
- 前端通过ajax将猜测值提交至后端,并输出结果
- 后端通过session存储真实值(使用mt_rand(1,100)生成随机数)
- 将用户提交的猜测值与真实值判断,并返回相应信息
创建guess.php(后端处理),index.html(前端页面) 代码如下(注释都写了,就不详细讲了):
index.html
<!DOCTYPE html>
<html>
<head>
<title>猜数字游戏</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="number" id="guessNumber" placeholder="输入你的猜测值">
<button id="submit">提交</button>
<script>
$('#submit').on('click',function() {
var guessNumber = $('#guessNumber').val();
if(!guessNumber) {
alert('请输入猜测值!');
} else {
$.get('./guess.php?num=' + guessNumber,function(data) {
alert(data);
});
}
});
</script>
</body>
</html>
guess.php
<?php
session_start();
if(!isset($_SESSION['number']))
$_SESSION['number'] = mt_rand(1,100);
$guessNumber = (int)$_REQUEST['num'];
if($guessNumber < $_SESSION['number'])
echo '猜小了!';
else if($guessNumber > $_SESSION['number'])
echo '猜大了!';
else {
echo '恭喜你猜对了!!';
unset($_SESSION['number']);
}
效果图:
|