前端jQuery使用ajax與后端Servlet進行數據交互


  前端代碼:

$.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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM