MyCalView.php
<html lang="en">
<head>
<title>我的计算器</title>
</head>
<script>
window.onload = function () {
var btn = document.getElementById('btn');
var num1 = document.getElementById('num1');
var num2 = document.getElementById('num2');
btn.onclick = function () {
if (isNaN(num1.value) || isNaN(num2.value)){
window.alert('输入的数值有误');
return false;
}
}
}
</script>
<body>
<h1>我的计算器</h1>
<form action="CalProcess.php" method="post">
<p>mun1 : <input type="text" name="num1" id="num1"></p>
<p>mun2 : <input type="text" name="num2" id="num2"></p>
<span>运算符: </span>
<select name="oper">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<p><input type="submit" value="提交" id="btn"></p>
</form>
</body>
</html>
<?php
OperService.php
<?php
//定义一个专门提供计算的类
class OperService{
public function getResult($num1,$num2,$oper){
switch ($oper){
case '+':
return $num1+$num2;
break;
case '-':
return $num1-$num2;
break;
case '*':
return $num1*$num2;
break;
case '/':
return $num1/$num2;
break;
default:
echo '操作符有误';
}
}
}
CalProcess.php
<?php
//引入计算类
require_once "OperService.php";
//获取参数
//$num1 = isset($_REQUEST['num1']) && is_numeric($_REQUEST['num1']) && !strpos('num1') ? $_REQUEST['num1'] : ''
if (isset($_REQUEST['num1']) && is_numeric($_REQUEST['num1'])){
$num1 = $_REQUEST['num1'];
}
if (isset($_REQUEST['num2']) && is_numeric($_REQUEST['num2'])){
$num2 = $_REQUEST['num2'];
}
if (isset($_REQUEST['oper'])){
$oper = $_REQUEST['oper'];
}
//创建对象
$operservice = new OperService();
echo $operservice->getResult($num1,$num2,$oper);