<%@ 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"> //get and post $(function(){ $("button:eq(0)").click(function(){ //get and post $.get("OneServlet",{name:"zhansgn",age:"12"},function(data){ alert(data); }); }); $("button:eq(2)").click(function(){ //json $.getJSON("type.json",function(data){ for(var i=0;i<data.length;i++) { var map=data[i]; alert(map.name+":"+map.age); } }); }); $("button:eq(3)").click(function(){ //json $.getScript("11.js"); }); $("button:eq(4)").click(function(){ //json $("div").load("11.html"); }); }); </script> </head> <body> <button >btn get</button> <button >btn post</button> <button >btn json</button> <button >btn script</button> <button >btn html</button> <div></div> </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); } }
对应的servlet配置
<servlet> <servlet-name>OneServlet</servlet-name> <servlet-class>song.yan.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/OneServlet</url-pattern> </servlet-mapping>
对应的json
[{ "name":"zangsan", "age":"22" },{ "name":"zangsan", "age":"12" },{ "name":"zangsan", "age":"232" }]
对应的js
alert("11");
对应的html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
HAHAHAHH
</body>
</html>