• 前端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

    既然选择了远方,便只顾风雨兼程
  • 相关阅读:
    zip 中文文件夹为空问题
    webview长按文本区域不显示文字放大镜等方法
    crash
    精疲力尽先生的造访
    告别忙碌的2017,迎来更加忙碌的2018
    传说中的59分!!
    为什么我一定吵不过女人?
    人挪活!
    低谷时,请读书!
    java小入门的感觉
  • 原文地址:https://www.cnblogs.com/Forever-Road/p/6107006.html
Copyright © 2020-2023  润新知