日期:2014-05-16  浏览次数:20574 次

JQuery和Ajax综合应用(二)

本篇继续上篇讲解第二个应用,做一个简单的加法计算器,也是分别使用$.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
	}

}