我正在尝试做什么
<小时/>我正在使用 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/