利用javascript、php和ajax实现计算器
计算器和ajax部分:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 16-9-2 * Time: 上午9:20 * * 计算器_GET * */ ?> <script type="text/javascript"> function loadXMLDoc(){ var xmlhttp; if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); //IE7+ FF GG else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//IE5 6 xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ //alert(xmlhttp.responseText); document.getElementById("result").value=xmlhttp.responseText; } } data1=document.getElementById("val1").value; dtype=document.getElementById("vtp").value; data2=document.getElementById("val2").value; xmlhttp.open("GET","test.php?data1="+data1+"&dtype="+dtype+"&data2="+data2, true); xmlhttp.send(); } </script> <p> <input type="text" name="val1" id="val1"> <select name="vtp" id="vtp"> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="del">/</option> </select> <input type="text" name="val2" id="val2"> <button id="calcBtn" onclick="loadXMLDoc()">=</button> <input type="text" name="result" id="result"> </p>
运算部分:
<?php $data1=floatval($_GET['data1']); $dtype=$_GET['dtype']; $data2=floatval($_GET['data2']); if($dtype!="add" && $dtype!="sub" && $dtype!="mul" && $dtype!="del") die("error"); if(empty($data1) || empty($data2)) die("error"); if($dtype=="del" && $data2==0) die("0"); $rwt=0; switch($dtype){ case "add": $rwt=$data1 + $data2; break; case "sub": $rwt=$data1 - $data2; break; case "mul": $rwt=$data1 * $data2; break; case "del": $rwt=$data1 / $data2; break; default: $rwt=0; } echo $rwt;
实现效果: