<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'test1.jsp' starting page</title> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <script type="text/javascript"> $(function(){ $("button").click(function(){ var param={ name:$("#name").val(), age:$("#age").val() }; $.ajax({ url:"OneServlet", data:param, beforeSend:function(){ $("img").show(); }, success:function(data) { alert(data); }, complete:function() { $("img").hide(); }, error:function(XMLHttpRequest,textStatus,errorThrown){ alert(XMLHttpRequest+" "+textStatus+" "+errorThrown); } }); }); }); </script> </head> <body> <form action=""> <input type="text" id="name"/><br> <input type="text" id="age"/><br> <button id="btn">btu</button> </form> <img src="html/3.jpg" style="display:none;"/> </body> </html>
对应的servlet
package song.yan; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class OneServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name=request.getParameter("name"); String age=request.getParameter("age"); out.print(name+":"+age); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }