日期:2014-05-16 浏览次数:20622 次
<script type="text/javascript"> var xmlHttpRequest = null;//声明一个变量来接受xmlHttpRequest对象 function ajaxSubmit() { if (window.ActiveXObject) {//这是IE浏览器 xmlHttpRequest new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) {//这是除IE外的其他浏览器 xmlHttpRequest = new XMLHttpRequest(); } if (xmlHttpRequest != null) { var v1 = document.getElementById("num1").value; var v2 = document.getElementById("num2").value; var v3 =document.getElementById("suanfa").value; if(!isNumber(v1) || !isNumber(v2)) { alert("请输入数字"); } else { xmlHttpRequest.open("POST", "jisuan", true); //POST请求,jisuanqi是servlet,true的是异步,false就是同步 //若取不到后台的值,"jisuan"要改为:"${pageContext.servletContext.contextPath }/jisuan" xmlHttpRequest.onreadystatechange = ajaxCallback;//关联好ajax的回调方法 xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") xmlHttpRequest.send("num1=" + v1 + "&num2=" + v2+"&suanfa="+v3); } } } function ajaxCallback() { if (xmlHttpRequest.readyState == 4) {//ReadyState共有5中状态(0,1,2,3,4) if (xmlHttpRequest.status == 200) {//200是正确的页面(错误如:404、500) var responseText = xmlHttpRequest.responseText; //alert(responseText); document.getElementById("results").value = responseText; } } } //进行是否是数字的验证 function isNumber(str){ var reg = /^\d+$/; for(var i=0; i<str.length; i++){ if(!str.charAt(i).match(reg)){ return false; }else if(i==str.length-1){ return true; } } } </script>
<input type="text" name="num1" id="num1"> <select name="suanfa" id="suanfa"> <option value="1"> + </option> <option value="2"> - </option> <option value="3"> * </option> <option value="4"> / </option> </select> <input type="text" name="num2" id="num2"> <input type="button" value="=" onclick=ajaxSubmit();> <input type="text" name="results" id="results">
System.out.println("==============doPost()方法运行==========="); response.setContentType("text/html;charset=utf-8"); // 禁止浏览器对此信息进行缓存 // 因为我们的AJAX请求可能会多次执行,每次都应该真正地发送请求到服务器 response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); PrintWriter out = response.getWriter(); String num1=request.getParameter("num1"); String num2=request.getParameter("num2"); String faze=request.getParameter("suanfa"); System.out.println(num1); System.out.println(num2); System.out.println(faze); int frist=Integer.valueOf(num1); int second=Integer.valueOf(num2); int result=0; if(faze.equals("1")) { result=frist+second; } if(faze.equals("2")) { result=frist-second; } if(faze.equals("3")) { result=frist*second; } if(faze.equals("4")) { if(second==0) { out.println("除数不可为零!"); } else { result=frist/second; } } out.println(result); out.flush(); out.close();