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

时间:2022-07-28 21:12:11

  前端代码:

$.ajax({
        //直接"post"或者"get",不需要"doPost","doGet",该函数到后端接收缓冲区会自动匹配
        type : "post",      
        //servlet文件名为Calculator,需要提前在web.xml里面注册
        url : "Calculator", 
        dataType : "text",  //数据类型,可以为json,xml等等,自己百度
        data :
        {
             "operator1" : operator1,        //操作数 
             "operatorSign":operatorSign,     //操作符
             "operator2":operator2            //操作数 
        },
        success : function(Result)
        {
               //Result为后端post函数传递来的数据,这里写结果操作代码
        },
        error : function(xhr, status, errMsg)
        {
             alert("数据传输失败!");
        }
    });

    后端servlet代码:

 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     {    //记得b = 0时自己处理 43             return a/b; 
44     }

     数据如何传回来,见:http://www.cnblogs.com/Forever-Road/p/6107031.html