簡單Ajax實現無刷新提交表單並獲取響應

login.jsp實現表單填寫頁面,結果提交到check.jsp,ajax後臺判斷check.jsp返回值。

代碼如下:

login.jsp

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>login!</title>
<script type="text/javascript">
	var xmlHttp=false;
	function createXMLHttpRequest(){
		if(window.ActiveXObject){
			try{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				try{
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(ee){
					xmlHttp=false;
				}
			}
		}
		else if(window.XMLHttpRequest){
			try{
				xmlHttp=new XMLHttpRequest();
			}
			catch(e){
				xmlHttp=false;
			}
		}
	}
	function check(){
		createXMLHttpRequest();
		xmlHttp.onreadystatechange=callback;
		nameStr=myform.name.value;
		passStr=myform.pass.value;
		var url="check.jsp?name="+nameStr+"&pass="+passStr;
		xmlHttp.open("post",url);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
		xmlHttp.send(null);
		function callback(){
			if(xmlHttp.readyState==4){
				if(xmlHttp.status==200){
					var str=xmlHttp.responseText;
					if(str=="ok"){
						document.getElementById("state").innerHTML="已登錄的用戶";
						var tdName=document.getElementById("tdName");
						tdName.replaceChild(document.createTextNode(nameStr),tdName.firstChild);
						var tdPass=document.getElementById("tdPass");
						tdPass.replaceChild(document.createTextNode(passStr),tdName.firstChild);
						var trButton=document.getElementById("button");
						trButton.innerHTML="<font color=\"red\">恭喜登錄成功!</font>";
					}else{
						document.getElementById("state").innerHTML="<font color=\"red\">用戶名或者密碼錯誤!</font>";
					}
				}
			}
		}
	}
</script>
</head>

<body><br>
	<div align="center" id="display">
		<form id="form1" name="myform">
			<strong><p id="state">未登錄用戶</p></strong>
			<table width="300" border="1" id="table">
				<tr>
					<td>用戶名:</td>
					<td id="tdName"><input type="text" id="userName" name="name"/></td>
				</tr>
				<tr>
					<td>密碼:</td>
					<td id="tdPass"><input type="password" id="userPass" name="pass"/></td>
				</tr>
				<tr>
					<td colspan="2">
						<div align="center" id="buttom">
							<input type="button" οnclick="check()" value="login"/>
							 
							<input type="reset" name="Submit2" value="reset" />
						</div>
					</td>
				</tr>
			</table>
			<p></p>
		</form>
	</div>
</body>
</html>

下面是check.jsp頁面,簡單起見,不做判斷了,直接返回結果:

<%
out.write("ok");
%>


瀏覽器訪問login.jsp,然後隨意輸入用戶名,點擊login按鈕後在表單上方顯示返回結果。 

 

Ps:關於xmlhttp.responseText返回值的問題,開始的時候沒注意,貌似返回的是整個頁面的html源代碼,導致我在回調函數裏總是判斷不成功,後來查看了jsp轉成servlet的代碼,才發現多輸出了兩行控制字符,這兩行多餘字符就是來自jsp頁面使用的標籤,servlet不輸出標籤內容,轉而輸出out.write("\r\n"),所以返回的不僅僅“ok”了。所以ajax裏判斷時需要做些處理,但是如果提交到一個servlet,那麼out.pirnt()什麼,就得到什麼,這是不同之處。

發佈了35 篇原創文章 · 獲贊 12 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章