java - 在某些 <div> 中显示 Servlet 响应

标签 java ajax jsp servlets

我正在尝试做什么

<小时/>

我正在使用 Netbeans 构建一个小型 Web 应用程序,它可以搜索邮政编码。布局是用 bootstrap.css 制作的。现在我在我的(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>

当单击按钮时,将调用 servlet 中的以下方法:

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);
    }

这给了我一个简单的 json 数组,它在新站点中打开,但我想在一些 <div> 中显示该响应在我的index.jsp 中。我怎样才能做到这一点?

最佳答案

你可以使用这样的东西

$.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); }
  }
);

关于java - 在某些 <div> 中显示 Servlet 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951889/

相关文章:

java - 如何将pojo属性转换为数据库列名

java - 如何使用java从xml(DOM)的多级标签中读取特定元素

Java - 按位比较和移位

javascript - create-react-app - 获取本地 JSON(通过 AJAX)

ajax - Internet Explorer错误

java - Web APP中添加Service层,在jsp上显示DB内容

java - 使用JSP上传的文件上传前需要编码吗?

java - 如何在 JSTL 中将一个字符串与另一个字符串分开

ruby-on-rails - Rails 4 - 缺少模板/缺少部分错误,仅在生产中

java - 如何在spring mvc中显示存储在数据库中的图像