首先创建一个 Servlet 类,它根据请求返回所需的响应。它可以是 HTML、XML 或 JSON。我建议为此使用JSON,因为这是在Java 中最容易生产和在JavaScript 中使用的最简单的方法。例如,您可以使用 Google Gson 将完全值得的 Java 对象转换为 JSON 字符串(反之亦然)。例如
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOexception {
// Populate response data somehow. Can be a String, Javabean or Collection/Map of either.
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", true);
data.put("message", "Hello World!");
data.put("param", request.getParameter("foo"));
// Write response data as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));
}
一旦 servlet 完成,只需按照通常的方式将其映射到 web.xml。例如。在url-pattern 的/firstServlet 上。
然后,在 jQuery 中,您可以使用 $.getJSON() 从给定资源中获取 JSON。第一个参数是 URL,显然是firstServlet。第二个参数是回调函数,您可以在其中处理返回的响应数据。我已经将请求参数foo 传递给纯粹的演示目的,这不是强制性的。
$.getJSON('firstServlet?foo=bar', function(data) {
alert('Success: ' + data.success + '\n'
+ 'Message: ' + data.message + '\n'
+ 'Param: ' + data.param);
});
您当然可以用它来做更多的事情,而不仅仅是显示一个简单的警报。例如。根据返回的数据操作/遍历当前页面中的 HTML DOM。
我之前在这里发布了两个带有实际示例的答案,您可能会发现它也很有用: