前端展示界面如下图所示,源代码见 ajaxDemo.jsp。
ajaxDemo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery 调用 Ajax 实现查询的局部更新</title>
</head>
<body>
查询信息:<input type="text" name="info" id="info">
<input type="submit" id="search"> <br>
<span id="show"></span>
<!-- 引入jQery -->
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
// 点击按钮触发
$("#search").click(function() {
var value = $("#info").val();
// 使用ajax发送请求
$.ajax({
type: 'POST', // 请求类型, 默认为 GET
url: "TestAjaxServlet", // 必需。规定把请求发送到哪个 URL。
data: "info="+value, // 可选。映射或字符串值。规定连同请求发送到服务器的数据。
success: function(result){ // 可选。请求成功时执行的回调函数。
// 展示结果
$("#show").html(result);
}
})
});
})
</script>
</body>
</html>
servlet 源文件,TestAjaxServlet.java
package com.syrdbt.system.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/TestAjaxServlet")
public class TestAjaxServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("info");
System.out.println("开始处理信息 " + name);
// 判断信息,将结果返回到前端
if(name.equals("abc")) {
response.getWriter().print("success");
} else {
response.getWriter().print("failed");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
测试结果截图: