<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>异步计数器</title>
<style>
form input {
width: 80px;
}
</style>
</head>
<body>
<form id="cal" action="calculate.php" onsubmit="return false">
<input type="number" name="num1" />
<select name="opt" id="">
<option value="1">+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
<option value="5">%</option>
</select>
<input type="number" name="num2" />
= <span>?</span>
<button>计算</button>
</form>
<script>
const btn = document.querySelector("button");
btn.addEventListener("click", calClick);
async function calClick() {
const num1 = document.forms.cal.num1.value;
const num2 = document.forms.cal.num2.value;
const opt = document.forms.cal.opt.value;
const response = await fetch(
"calculate.php?num1=" + num1 + "&opt=" + opt + "&num2=" + num2
);
const comments = await response.json();
const res = document.querySelector("form span");
res.textContent = comments;
}
</script>
</body>
</html>
<?php
$num1=$_GET['num1'];
$num2=$_GET['num2'];
$opt=$_GET['opt'];
$res=0;
switch($opt){
case "1":
$res = $num1 + $num2;
break;
case "2":
$res = $num1 - $num2;
break;
case "3":
$res = $num1 * $num2;
break;
case "4":
if($num2==0){
$res="除数不能是0";
break;
}
$res = $num1 / $num2;
break;
case "5":
if($num2==0){
$res="除数不能是0";
break;
}
$res = $num1 % $num2;
break;
}
echo json_encode($res);