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, HttpServletResponse response) throws ServletException, 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(); }}
截圖: