RAW
RAW

Reputation: 7825

Show Servlet Response in some <div>

What I'm trying to do


I'm building a small webapp with Netbeans, which can search for a ZIP-Code. The layout is made with bootstrap.css. Now I made following form in my (index.jsp):

<form id="form_submit_search"
                      class="navbar-form navbar-right" 
                      role="form"
                      action="zipSearchHandler" 
                      method="get">

                        <div class="form-group">
                            <input name="tv_zip" 
                                   type="text" 
                                   placeholder="ZIP Code..." 
                                   class="form-control"> 
                        </div>

                        <button id="submit_search" 
                                type="submit" 
                                class="btn btn-success">Search</button>
                </form>

When the Button is klicked following method in the servlet is getting called:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String zipCode = request.getParameter("tv_zip");
        System.out.println(zipCode + " habe den zip bekommen");

        response.setContentType("text/html;charset=UTF-8");
        List<String> list = new ArrayList<String>();
        list.add("item1");
        list.add("item2");
        list.add("item3");
        list.add(zipCode);
        String json = new Gson().toJson(list);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

This give's me back a simple json-array, which is opened in a new site, but I'd like to show that response in some <div> in my index.jsp. How can I do that?

Upvotes: 0

Views: 2562

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

You could use something like this

$.ajax(
  {
    type: "POST", 
    url: "/TestServlet",
    data: { tv_zip: '90210' }, // zipcode
    dataType: "json",
    success: function(response) {
      // replace the contents of div with id=some_div with the response.
      // You will want to format / tweak this.
      $('#some_div').html(response); 
    },
    error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
  }
);

Upvotes: 2

Related Questions