1. 程式人生 > >Ajax底層原理及相關小案例

Ajax底層原理及相關小案例

Ajax的最大特點是:非同步訪問、區域性重新整理。核心是:XML。

Ajax的關鍵技術:

1.使用css搭建介面樣式,負責頁面的排版和美工

2.使用DOM進行動態顯示和互動,對頁面進行區域性修改

3.使用XMLHttpRequest非同步獲取資料

4.使用JavaScript將所有的元素綁在一起

Ajax執行過程:

第一步:建立XMLHttpRequest物件

(注:不同的瀏覽器建立方式不同,可以提取為方法來進行呼叫)

function createXMLHttpRequest(){
	 if(window.ActiveOBject){
	   //IE瀏覽器 
	   xhr =  new window.ActiveOBject("Microsoft.XMLHTTP");
	 }else{ 
           //其他瀏覽器 
	   xhr = new XMLHttpRequest();
	 }	
     }
第二步:建立到伺服器的連線
//get方式  
xhr.open("get", "http://localhost:8080/hdk/index.jsp?name="+name);  
//post方式  xhr.open("post","http://localhost:8080/hdk/index.jsp?name="+name);  
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
(上述連線方式是通過一個使用者名稱的驗證案例來寫的,伺服器的路徑是驗證資訊跳轉的jsp)
第三步:指定回撥函式
(注:不同的Ajax響應回來後會自動呼叫函式,不同的Ajax請求步驟基本相同,但是差別和難易主要是在回撥函式)
function process(){
	  if(xhr.readyState == 4){
	     if(xhr.status == 200){
	     //200  404  500
	     //得到返回結果
	     var result = xhr.requestText;
	     //寫到指定位置
	     document.getElementById("nametip");
          }else{
	    alert("Ajax請求錯誤");
	} 
      }
  }
在Ajax應用程式中,需要了解五種就緒狀態,但通常只使用狀態4。Http就緒狀態,表示請求的狀態或情形。 0(未初始化):請求沒有發出(在呼叫open()之前) 1(初始化):請求已經建立但沒發出(在呼叫send()之前) 2(傳送資料):請求已經發出正在處理中(可以從響應得到資料的頭部) 3(資料傳送中):請求已經處理,響應中有部分資料可用,但是伺服器還沒完成響應 4(完成):響應已完成,可以訪問伺服器響應並使用它 狀態碼 status: 200,404,500

返回結果資料:requestText、responseXML

第四步:傳送請求

//get方式
xhr.send(null);
//post方式
xhr.send("name"+name);
注:1.如果是get請求,引數已經附加在url中,採用send(null)即可。如果是post請求,需要通過send()來傳遞引數
    2.如果是post請求,要在send之前新增如下語句來指定http header:
xmlHttp.setRequestHeader("Content-Type“,"application/x-www-form-urlencoded");
其他:
XMLHttpRequest物件是Ajax應用的核心
1.屬性
-readyState:提供當前HTML的就緒狀態
-status:伺服器響應的狀態程式碼
-responseText/responseXML:伺服器返回的請求響應文字/XML
2.方法
-open():建立到伺服器的新請求
-send():向伺服器傳送請求
-setRequestHeader():設定請求頭資訊
3.事件
-onreadystatechange:用於指定回撥函式

小案例:


user.jsp主要程式碼:

<%@ 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 'user.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">
	-->

  </head>
  	<script type="text/javascript">
  		var xhr;
  		function checkName(){
  			//獲取使用者名稱
  			var name = document.getElementById("name").value;
  			
  			//判斷使用者名稱是否為空(JS)
  			if(name == ""){
  				document.getElementById("nametip").innerHTML="使用者名稱不能為空";
  				return;
  			}
  			//判斷使用者名稱是否可用(ajax)
  			//1.建立XMLHttpRequest物件
  			createXMLHttpRequest();
  			//2.和伺服器建立連線
  			//get方式
  			//xhr.open("get", "http://localhost:8080/hdk/index.jsp?name="+name);
  			//post方式
  			xhr.open("post","http://localhost:8080/hdk/index.jsp?name="+name);
  			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  			//3.指定回撥函式(ajax響應回來以後自動呼叫的函式)
			xhr.onreadystatechange=process;
  			
  			//4.傳送請求給伺服器
  			//get方式
  			//xhr.send(null);
  			//post方式
  			xhr.send("name"+name);
  		}
  		//判斷一般瀏覽器和ie瀏覽器的區別
  		function createXMLHttpRequest(){
  			if(window.ActiveXObject){//ie瀏覽器
  				xhr = new window.ActiveXObject("Microsoft.XMLHTTP");
  			}else{
  				xhr = new XMLHttpRequest();
  			}
  		}
  		
  		function process(){
  			if(xhr.readyState == 4){
  				//縮短ajax請求的時間
  				if(xhr.status == 200){
  				//獲取ajax的返回結果
  		  		var result = xhr.responseText;
  		  		//寫到指定的位置
  		  		document.getElementById("nametip").innerHTML=result;
  				
  				}else{
  				alert("ajax請求失敗");
  				}	
  		}
  	}
  	</script>
  <body>
  	<form action=""  method="post"  >
   		姓名<input type="text" name="name" id="name"   onblur="checkName( )"><span id="nametip"></span>   <br>
   		密碼<input type="text" name="pwd" id="pwd"><br>
   		密碼<input type="text" name="repwd" id="repwd"><br>
   	    <input type="submit" value="提交">
   </form>
  
  </body>
</html>
index.jsp程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
  		//獲取使用者名稱
  		String name = request.getParameter("name");
  		
  		//判斷是否能用
  		boolean flag = false;
  		if(name.indexOf("sxt")>=0){
  			flag = true;
  		}
  		
  		//給出客戶端提示資訊
  		if(flag){
  			out.print("使用者名稱已經被佔用");
  		}else{
  			out.print("使用者名稱可以使用");
  		}
  	%>