JQuery和Ajax綜合應用(二)

來源:互聯網
上載者:User

本篇繼續上篇講解第二個應用,做一個簡單的加法計算機,也是分別使用$.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}}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.