【问题标题】:How to retrieve multiple values from servlet in jsp using AJAX如何使用 AJAX 从 jsp 中的 servlet 中检索多个值
【发布时间】:2018-10-29 14:07:19
【问题描述】:

我有这个ajax javascript 代码调用servlet 来检索两个值(名字、电话)。我知道如何从 servlet 中获取单个值而不是多个值。

这是我的ajax

    <script>
        function getCustomerDetailsAjax(str) {
            str = $('#customerId').val();

            if (document.getElementById('customerId').value <= 0) {
                document.getElementById('firstName').value = " ";
                document.getElementById('telephone').value = " ";
                document.getElementById('vehicleMake').value = " ";
                document.getElementById('vehicleModel').value = " ";
                document.getElementById('vehicleColor').value = " ";
            } else {
                $.ajax({
                    url: "GetCustomerDetails",
                    type: 'POST',
                    data: {customerId: str},
                    success: function (data) {                       
                        alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
                    }
                });
            }
        }
    </script>

这是我的servlet

public class GetCustomerDetails extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out=response.getWriter();
    int customerId = Integer.valueOf(request.getParameter("customerId"));
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
        PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
        ps.setInt(1, customerId);
        ResultSet result=ps.executeQuery();
        if(result.next()){
            out.print(result.getString("firstname")); //I want to send this value
            out.print(result.getString("telephone")); //and this value

        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    }

}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

这是从servlet中检索数据的部分,如何从中获取多个值并发出警报?

       success: function (data) {                       
            alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
       }

谢谢!

【问题讨论】:

  • 有人能帮帮我吗?
  • 嗨。要在 Web 服务和客户端之间共享数据,您必须选择最适合您需求的协议/策略(XML、JSON...)。由于您使用的是 javascript,因此我建议您阅读 JSON(代表“JavaScript Object Notation”)。在您的示例中,您应该生成并返回一个 JSON 字符串(带有正确的 Content-type 标头) - 阅读有关 javax.json 包的信息。使用 JSON,您可以返回包含您选择的字段的数据结构。
  • @mrlew 你能告诉我一些例子吗?很大的帮助
  • 我发布了一个答案。希望对您有所帮助。

标签: javascript java ajax servlets


【解决方案1】:

要在您的网络服务和客户端之间共享数据,您必须选择最适合您需求的协议/策略(XML、JSON...)。

由于您使用的是 JavaScript,我建议您阅读 JSON(代表“JavaScript Object Notation”)。

在您的示例中,您应该生成并返回一个 JSON 字符串(带有正确的 Content-type 标头) - 您可以阅读有关 javax.json 包的信息。使用 JSON,您可以返回包含您选择的字段的数据结构。

类似的东西(未经测试 - 我已经很久没有编写 Java 代码了):

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out=response.getWriter();
    int customerId = Integer.valueOf(request.getParameter("customerId"));
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
        PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
        ps.setInt(1, customerId);
        ResultSet result=ps.executeQuery();
        if(result.next()){

            /* set response content type header: jQuery parses automatically response into a javascript object */
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            /* construct your json */
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.put("firstname", result.getString("firstname"));
            jsonResponse.put("telephone", result.getString("telephone"));            

            /* send to the client the JSON string */
            response.getWriter().write(jsonResponse.toString());
           // "{"firstname":"first name from db","telephone":"telephone from db"}"

        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    }

}

在你的 JS 中(我想你正在使用 jQuery,因为 success 回调):

   success: function (data) { 
        /* because you set the content-type header as 'application/json', you'll receive an already parsed javascript object - don't need to use JSON.parse. */


        console.log(data);
        /*
            {
                firstname: "first name from db",
                telephone: "telephone from db"
            }

        */

        alert(data.firstname); //alert firstname
        alert(data.telephone); //alert phone
   }

【讨论】:

    【解决方案2】:

    是的,您可以使用 JSON 来执行此操作,正如前面的答案已经说明的那样,但我想补充一点,由于您使用的是 jquery,因此您可以做一些事情来进一步简化您的代码。

       <script>
            function getCustomerDetailsAjax(str) {
                str = $('#customerId').val();
    
                if (str <= 0) {
                    $('#firstName').val(" ");
                    $('#telephone').val(" ");
                    $('#vehicleMake').val(" ");
                    $('#vehicleModel').val(" ");
                    $('#vehicleColor').val(" ");
                    $('#firstName').val(" ");
                } else {
    
              //with jquery you can do this, which is much easier.
              var params = {customerId: str}; //set paramaters
              $.post("GetCustomerDetails", $.param(params), function(responseJson) {
                  //handle response
                  var firstname = responseJson.firstname;
                  var telephone = responseJson.telephone;
    
                //now do whatever you want with your variables
    
               });
    
                }
    
            }
        </script>
    

    另外,这里有一些变化:

    public class GetCustomerDetails extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        int customerId = Integer.valueOf(request.getParameter("customerId"));
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
            PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
            ps.setInt(1, customerId);
            ResultSet result=ps.executeQuery();
            if(result.next()){
    
            String firstname = result.getString(1); //firstname
            String telephone = result.getString(2); //telephone
    
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.put("firstname", firstname);
            jsonResponse.put("telephone", telephone);   
    
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jsonResponse.toString());
    
            }
    
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    }
    

    还有其他方法可以将值从 servlet 发送到 jsp/html 页面。我强烈建议在How to use Servlets and Ajax 上查看 BalusC 的答案,这非常有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2012-05-12
      • 2015-04-11
      相关资源
      最近更新 更多