<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>calc_AJAX.html</title>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","calc_AJAX.php",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("num1=1&num2=2&add=0");
}
</script>
</head>
<body>
<form method="post" action="">
计算器<br>
数值1:<input type="text" name="num1" value="3"> <br>
数值2:<input type="text" name="num2" value="2"> <br>
<br>
<button type="button" name="add" value="+" οnclick="loadXMLDoc()">+ </button>
<button type="button" name="sub" value="-" οnclick="loadXMLDoc()"> -</button>
<button type="button" name="mul" value="*" οnclick="loadXMLDoc()"> *</button>
<button type="button" name="div" value="/" οnclick="loadXMLDoc()"> /</button>
<br>
结果:<br>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
</form>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta charset="UTF-8">
<title>calc_AJAX.php</title>
</head>
<body>
<?php
$sum="";
//$num1=$_POST['num1'];
// $num2=$_POST['num2'];
$num1=isset($_POST['num1']) ? $_POST['num1'] : "";
$num2=isset($_POST['num2']) ? $_POST['num2'] : "";
if(is_numeric($num1) && is_numeric($num2)){
if(isset($_POST['div'])){
if($num2 ===0){
echo "除数不能为0";
exit(0);
}else{
$sum=$num1/$num2;
}
}
else if(isset($_POST['add'])){
$sum=$num1+$num2;
}
else if(isset($_POST['sub'])){
$sum=$num1-$num2;
}
else if(isset($_POST['mul'])){
$sum=$num1*$num2;
}
else{
echo "计算符无效";
exit(0);
}
}else{
echo "请输入有效数值";
exit(0);
}
echo $sum;
?>
</body>
</html>