Front-End Code:
1 $.ajax ({2Type: "POST",3URL: "Calculator",//The servlet file is named Calculator and needs to be registered in Web. XML in advance4DataType: "Text",5 Data:6 {7"Operator1": Operator1,//Number of operands8"Operatorsign": Operatorsign,//operator9"Operator2": Operator2//Number of operandsTen }, OneSuccess:function(Result) A { - //Result is the data passed to the back-end post function, where the resulting operation code is written - }, theError:function(XHR, status, ErrMsg) - { -Alert ("Data transfer failed!")); - } +});
Back-End Code:
1 protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {2 //The following data is received3 DoubleOperator1 = double.parsedouble (Request.getparameter ("Operator1"));4String operatorsign = Request.getparameter ("Operatorsign");5 DoubleOperator2 = double.parsedouble (Request.getparameter ("Operator2"));6 7 if(Operatorsign.equals ("+"))8 {9PrintWriter out = Response.getwriter ();//Set Transfer parametricTenOut.print (Add (Operator1, Operator2));//results to the front end One } A Else if(Operatorsign.equals ("-")) - { -PrintWriter out =Response.getwriter (); the Out.print (Sub (Operator1, Operator2)); - } - Else if(Operatorsign.equals ("*")) - { +PrintWriter out =Response.getwriter (); - Out.print (mult (Operator1, Operator2)); + } A Else if(Operatorsign.equals ("/")) at { -PrintWriter out =Response.getwriter (); - out.print (Dev (operator1, Operator2)); - } - } - Public DoubleAddDoubleADoubleb) in { - returnA +b; to } + - Public DoubleSubDoubleADoubleb) the { * returnA-b; $ }Panax Notoginseng Public DoubleMultDoubleADoubleb) - { the returnA *b; + } A Public DoubleDevDoubleADoubleb) the { + returnA/b; -}
Front-end jquery uses Ajax to interact with back-end servlet data