AJAX = 非同步 JavaScript 和 XML。 AJAX 是一種用於建立快速動態網頁的技術。通過在後台與伺服器進行少量資料交換,AJAX 可以使網頁實現非同步更新。這意味著可以在不重新載入整個網頁的情況下,對網頁的某部分進行更新。這就是AJAX的優勢了,可以使網頁從伺服器請求少量的資訊,而不是整個頁面。 下面通過一個簡單的小案例協助大家進一步理解AJAX,先看: 1: 前台是一個簡單的擷取當前頁面的值和AJAX,已給出相應的注釋,不懂留言:
<%@ 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 'Login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">function btn_click(){//建立XMLHttpRequest對象var xmlHttp;xmlHttp=new XMLHttpRequest();try{//相容Firefox,Opera8.0+,SafarixmlHttp=new XMLHttpRequest();}catch(e){//相容IEtry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){alert("您的瀏覽器不支援ajax");return false;}}}//擷取文字框的值var username=document.getElementById("txt_username").value;var password=document.getElementById("txt_password").value;//設定編碼,避免中文出現亂碼。username=encodeURIComponent(encodeURIComponent(username));//配置XMLHttpRequest對象xmlHttp.open("GET","servlet/LoginServlet?username="+username+"&password="+password,true);//設定回呼函數xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==0){docuement.getElementById("result").innerHTML="未初始化.還沒調用open()..";}else if(xmlHttp.readyState==1){docuement.getElementById("result").innerHTML="正在串連伺服器.還沒調用send()..";}else if(xmlHttp.readyState==2){docuement.getElementById("result").innerHTML="正在載入資訊...";}else if(xmlHttp.readyState==3){docuement.getElementById("result").innerHTML="正在連收資料...";}else if(xmlHttp.readyState==4){//表示互動完畢if(xmlHttp.status==200){//200對應ok ,document.getElementById("result").innerHTML=xmlHttp.responseText;}else{docuement.getElementById("result").innerHTML="出錯了";}}else{docuement.getElementById("result").innerHTML="網路異常...";}}xmlHttp.send(null);}</script> </head> <body> <label>姓名:</label><input type="text" id="txt_username"/><br/> <label>密碼:</label><input type="password" id="txt_password"/><br/> <input type="button" value="擷取文字框的值" id="btn" onclick="btn_click()"/><br/> <div id="result"></div> </body></html>
2. 後台是一個servlet 主要是接收前台傳過來的值並且為前台提供必要的值,代碼如下:
package servlet;import java.io.IOException;import java.io.PrintWriter;import java.net.URLDecoder;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();String username=request.getParameter("username");//設定編碼,避免出現亂碼username = URLDecoder.decode(username, "utf-8");String password=request.getParameter("password");System.out.println("username----"+username+"<br>password----"+password+"<br>date----"+new Date());out.println("username----"+username+"<br>password----"+password+"<br>date----"+new Date());}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}}
3.設定檔web.xml如下:
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 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_2_5.xsd"> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
這是本人學AJAX寫的第一個例子,寫的不足之處望見諒,指出缺點,不勝感激。