1.index.html
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>test load()</title> <script type="text/javascript" src="script/jquery-3.1.1.js"></script> <script type="text/javascript"> $(function() { $("input:eq(0)").click(function() { $("#content").load("LoadServlet"); //$("#content").load("LoadServlet #myli");//过滤筛选 }); $("input:eq(1)").click(function() { $("#content").load("LoadServlet",{'username':'Haige','age':30},function(responseText,textStatus,XMLHttpRequest){ // alert(textStatus);//获取服务端传回数据的状态 // alert(responseText);//服务端传回的文本数据 // alert(XMLHttpRequest.status);//服务端传回异步处理对象 alert(XMLHttpRequest。responseText); });//过滤筛选 }); }); </script> </head> <body> <input type="button" value="加载get方法"/> <input type="button" value="加载Post方法"/> <div id="content"></div> </body> </html>
LoadServlet.java
package com.haige; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/LoadServlet") public class LoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoadServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out =response.getWriter(); out.println("<ul id='myul'>"); out.println("<li id='myli'>北京</li>"); out.println("<li>上海</li>"); out.println("<li>南京</li>"); out.println("</ul>"); out.close(); } protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String username=request.getParameter("username"); int age=Integer.parseInt(request.getParameter("age")); response.setCharacterEncoding("utf-8"); PrintWriter out =response.getWriter(); out.println("<p>我的名字叫:"+username+",今年"+age+"岁</p>"); out.close(); } }
截图: