前端jQuery使用ajax与后端Servlet进行数据交互
Posted Forever-Road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端jQuery使用ajax与后端Servlet进行数据交互相关的知识,希望对你有一定的参考价值。
前端代码:
1 $.ajax({ 2 type : "post", 3 url : "Calculator", //servlet文件名为Calculator,需要提前在web.xml里面注册 4 dataType : "text", 5 data : 6 { 7 "operator1" : operator1, //操作数 8 "operatorSign":operatorSign, //操作符 9 "operator2":operator2 //操作数 10 }, 11 success : function(Result) 12 { 13 //Result为后端post函数传递来的数据,这里写结果操作代码 14 }, 15 error : function(xhr, status, errMsg) 16 { 17 alert("数据传输失败!"); 18 } 19 });
后端代码:
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 //以下为接收数据 3 double operator1 = Double.parseDouble(request.getParameter("operator1")); 4 String operatorSign = request.getParameter("operatorSign"); 5 double operator2 = Double.parseDouble(request.getParameter("operator2")); 6 7 if(operatorSign.equals("+")) 8 { 9 PrintWriter out = response.getWriter(); //设定传参变量 10 out.print(add(operator1, operator2)); //结果传到前端 11 } 12 else if (operatorSign.equals("-")) 13 { 14 PrintWriter out = response.getWriter(); 15 out.print(sub(operator1, operator2)); 16 } 17 else if (operatorSign.equals("*")) 18 { 19 PrintWriter out = response.getWriter(); 20 out.print(mult(operator1, operator2)); 21 } 22 else if (operatorSign.equals("/")) 23 { 24 PrintWriter out = response.getWriter(); 25 out.print(dev(operator1, operator2)); 26 } 27 } 28 public double add(double a,double b) 29 { 30 return a+b; 31 } 32 33 public double sub(double a,double b) 34 { 35 return a-b; 36 } 37 public double mult(double a,double b) 38 { 39 return a*b; 40 } 41 public double dev(double a,double b) 42 { 43 return a/b; 44 }
以上是关于前端jQuery使用ajax与后端Servlet进行数据交互的主要内容,如果未能解决你的问题,请参考以下文章