简单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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章