在某些<div>方面显示 Servlet 响应



我要做的事情


我正在用Netbeans构建一个小型网络应用程序,它可以搜索邮政编码。布局是用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数组,它在一个新的站点中打开,但我想在我的index.jsp中的一些<div>中显示该响应。我该怎么做?

您可以使用类似的东西

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

最新更新