Как получить несколько значений из сервлета в JSP с помощью AJAX - PullRequest
0 голосов
/ 19 мая 2018

У меня есть ajax код JavaScript, который вызывает 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?
       }

Спасибо!

Ответы [ 2 ]

0 голосов
/ 19 мая 2018

Да, вы можете сделать это с 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);
    }

}

Существуют и другие способы отправки значений из вашего сервлета на страницу jsp / html.Я настоятельно рекомендую проверить ответ BalusC здесь Как использовать сервлеты и Ajax , это чрезвычайно полезно.

0 голосов
/ 19 мая 2018

Чтобы обмениваться данными между вашим веб-сервисом и клиентом, вы должны выбрать протокол / стратегию, которая наилучшим образом соответствует вашим потребностям (XML, JSON ...).

Поскольку вы используете JavaScript, я рекомендуючтение о JSON (расшифровывается как «JavaScript Object Notation»).

В вашем примере вы должны сгенерировать и вернуть строку JSON (с правильными заголовками типа контента) - вы можете прочитать о пакете 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
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...