<!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="+" onclick="loadXMLDoc()">+ </button>
<button type="button" name="sub" value="-" onclick="loadXMLDoc()"> -</button>
<button type="button" name="mul" value="*" onclick="loadXMLDoc()"> *</button>
<button type="button" name="div" value="/" onclick="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>
原文链接:https://www.f2er.com/ajax/162421.html