码迷,mamicode.com
首页 > Web开发 > 详细

前端jQuery使用ajax与后端Servlet进行数据交互

时间:2016-11-27 22:30:57      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:使用   ajax   equal   except   sig   string   style   代码   数据传输   

  前端代码:

 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进行数据交互

标签:使用   ajax   equal   except   sig   string   style   代码   数据传输   

原文地址:http://www.cnblogs.com/Forever-Road/p/6107006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!