前端jQuery使用ajax與後端Servlet進行資料互動

來源:互聯網
上載者:User

標籤:使用   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進行資料互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.