Ajax完成用戶名的異步校驗

	function checkUsername() {
		var username = document.getElementById("username").value;
		//1. 創建異步對象
		 var xhr = CreateXHR();
		//2. 設置監聽
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
				//將接收到 reponseText 輸出到 span 中
					document.getElementById("span1").innerHTML = xhr.responseText;			
				}
			}
		}
		//3. 打開鏈接
		//open 方法的三個參數 <1>發送方式。<2>請求的 URL(絕對路徑),<3>是否異步
		xhr.open("GET", "${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username, true)
		//4. 發送
		xhr.send(null);
	}
	
	//在發送時爲了避免瀏覽器緩存文件,在URL 添加time屬性,使請求唯一。
	
	//創建異步對象
	function CreateXHR() {
			var XHR = false;
			try {
				XHR = new ActionXObject("msxml2.XMLHTTP");
			} catch (e1) {
				try {
					xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
				} catch (e2) {
					try {
						XHR = new XMLHttpRequest();
					} catch (e3) {
						XHR = false;
					}
				}
			}
			return XHR;
		}
	
	

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章