微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

简单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" onclick="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()什么,就得到什么,这是不同之处。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐