1.
<!DOCTYPE html><html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btn").click(function(){ //從文字框中擷取內容 var userName = document.getElementById("UserName").value; //load()方法從伺服器載入資料,並把返回的資料放入被選元素中。 //GET方式 $('#message').load("AJAX?name=" + userName); //POST方式 //$('#message').load("AJAX?name=" + userName,{"Content-type":"application/x-www-form-urlencoded"}); }); }); </script> </head> <body> <input type="text" id="UserName" value="admin"/> <input type="button" id="btn" value="校正使用者名稱"/> <br/> <div id="message"></div> </body></html>
//GET方式 $('#message').load("AJAX?name="+ userName); //POST方式 //$('#message').load("AJAX?name="+userName,{"Content-type":"application/x-www-form-urlencoded"});
服務端
//服務端public class AJAX extends HttpServlet { //伺服器端代碼 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String old = request.getParameter("name"); if (old == null) { out.println("使用者名稱不可為空"); }else{ String name = new String(old.getBytes("ISO8859-1"),"gb2312"); //String name = URLDecoder.decode(old,"utf-8"); System.out.println(name); if (name.equals("j")) { out.println("使用者名稱[" + name +"]已經存在,請使用其他使用者名稱"); }else{ out.println("使用者名稱[" + name +"]尚未存在,可以使用"); } //out.println("<a href=\"classic.html\">返回校正頁面</a>"); } } finally { out.close(); } }
XML
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>AJAX</servlet-name> <servlet-class>AJAX</servlet-class> <load-on-startup>1</load-on-startup> </servlet><servlet-mapping> <servlet-name>AJAX</servlet-name> <url-pattern>/AJAX</url-pattern> </servlet-mapping><session-config> <session-timeout> 30 </session-timeout> </session-config></web-app>
...
$(selector).load(url,data,callback)把遠端資料載入到被選的元素中$.ajax(options)把遠端資料載入到XMLHttpRequest 對象中$.get(url,data,callback,type)
$.post(url,data,callback,type)使用HTTP GET 來載入遠端資料$.getJSON(url,data,callback)使用HTTP GET 來載入遠程 JSON 資料$.getScript(url,callback)載入並執行遠端JavaScript 檔案