本篇繼續上篇講解第二個應用,做一個簡單的加法計算機,也是分別使用$.ajax(),$.get(),$.post()方法分別實現,與之前不同的是,現在要從前台輸入要計算的數字,並且將計算結果返回到前台頁面。
將html頁面貼上來,如果前面一篇文章讀懂了,這篇文章將非常容易:
<script type="text/javascript" src="js/jquery.js"></script><title>Jquery和ajax完成簡單的加法計算機</title><script type="text/javascript">$(document).ready(function(){$("#btn1").click(function(){$.ajax({type:"GET",url:"ComputeServlet",dataType:"html",data:{num1:$("#num1").val(),num2:$("#num2").val()},success:function(param){$("#result").val(param);}});});$("#btn2").click(function(){$.ajax({type:"POST",url:"ComputeServlet",dataType:"html",data:{num1:$("#num1").val(),num2:$("#num2").val()},success:function(param){$("#result").val(param);}});});$("#btn3").click(function(){$.get("ComputeServlet",{num1:$("#num1").val(),num2:$("#num2").val()},function(params){$("#result").val(params);});});$("#btn4").click(function(){$.post("ComputeServlet",{num1:$("#num1").val(),num2:$("#num2").val()},function(params){$("#result").val(params);});});});</script></head><body><input type="text" name="num1" id="num1">+<input type="text" name="num2" id="num2">=<input type="text" name="result" id="result"><br><input type="submit" value="計算1" id="btn1"><input type="submit" value="計算2" id="btn2"><input type="submit" value="計算3" id="btn3"><input type="submit" value="計算4" id="btn4"></body>
啟動並執行的介面如下:
對於的servlet如下:
public class ComputeServlet extends HttpServlet{public void destroy(){super.destroy(); }public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{System.out.println("get++++++++++");response.setContentType("text/html");PrintWriter out = response.getWriter();String num1=request.getParameter("num1");String num2=request.getParameter("num2");System.out.println("num1====>"+num1);System.out.println("num2====>"+num2);if(num1!=null && num2!=null){out.print(Integer.parseInt(num1)+Integer.parseInt(num2));}else{out.print("invalide");}out.flush();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{this.doGet(request, response);}public void init() throws ServletException{// Put your code here}}