Ajax异步校验

        Ajax(Asynchronous Javascript And XML)构建网页的一种综合使用JavaScript和XML的技术,HTML网页的异步传输技术:在等待网页的传输过程中,用户依然可以和系统进行交互,页面不用刷新就可以更新内容,合理的运用可以让用户感觉更好更方便。


           不用Ajax时,浏览器request请求,发送到tomcat服务器上面,然后tomcat生成html页面再返回到浏览器,返回页面期间只能等待程序,不能做任何其他的事情,直至html页面返回才能有刷新的效果,重新渲染页面,这样使用户的使用度感觉起来很不好。


         在浏览器里有一个Ajax引擎,其与tomcat与java没有任何关系,它是在浏览器里执行的。使用Ajax后,发送一个请求给浏览器里的Ajax引擎,可以看做是一个中转服务,然后让Ajax引擎去和tomcat交互,浏览器继续自己的工作,不必等待tomcat返回html刷新页面,实现异步操作,tomcat服务发送html到引擎,然后我们再操作引擎通过JavaScript把引擎里的东西拿出来,通过DOM主动返回到浏览器。

Ajax和之前相比多了XMLHttpRequest对象,

XMLHttpRequest对象的属性


readyState的几个值表示引擎的状态,0—未初始化,1—装载中,2—已经装载,3—交互中,4—完成。通常用的就是4,表示引擎完成了,我们的请求是成功的,引擎的整个初始化是完成的。

responseTest利用JavaScript把Ajax引擎的东西拿到浏览器中,返回文本,text或者xml

status:Ajax引擎和tomcat交互时,用的是http协议,返回200表示成功,或者404 没找到页面 、500系统内部错误等,用status状态判断http协议是否正确

statesText返回错误文本,比如404的描述信息。




open方法(method传送方式get 或是post,请求的资源是哪个jsp,默认为异步true)设置一些信息

send方法,把设置的信息发送给引擎,这才是真正起作用的,get请求的话send的参数为null。

onreadystatechange事件,当Ajax引擎的状态改变的时候要响应这个事件,接收到引擎的内部状态,为4时为成功状态,从引擎里tomcat返回的东西拿出来。

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ page import="com.bjpowernode.drp.sysmgr.domain.*" %> 
<%@ page import="com.bjpowernode.drp.sysmgr.manager.*" %>   
<%
	request.setCharacterEncoding("GB18030");
	String command = request.getParameter("command");
	String userId = "";
	String userName = "";
	String contactTel = "";
	String email = "";
	//Thread.currentThread().sleep(3000);
	
	if ("add".equals(command)) {	
		if (UserManager.getInstance().findUserById(request.getParameter("userId")) == null) { 
			User user = new User();
			user.setUserId(request.getParameter("userId"));
			user.setUserName(request.getParameter("userName"));
			user.setPassword(request.getParameter("password"));
			user.setContactTel(request.getParameter("contactTel"));
			user.setEmail(request.getParameter("email"));
			
			UserManager.getInstance().addUser(user);
			out.println("添加用户成功!");
		}else {
			userId = request.getParameter("userId");
			userName = request.getParameter("userName");
			contactTel = request.getParameter("contactTel");
			email = request.getParameter("email");
			out.println("用户代码已经存在,代码=【" + request.getParameter("userId") + "】");		
		}
	}
%>    
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
		<title>添加用户</title>
		<link rel="stylesheet" href="../style/drp.css">
		<script src="../script/client_validate.js"></script>
		<script type="text/javascript">
	function goBack() {
		window.self.location="user_maint.html"
	}
	
	function addUser() {
		var userIdField = document.getElementById("userId");
		//用户代码不能为空
		if (trim(userIdField.value) == "" ) {
			alert("用户代码不能为空!");
			userIdField.focus();
			return;
		}
		//用户代码至少四个字符
		if (trim(userIdField.value).length < 4) {
			alert("用户代码至少4个字符!");
			userIdField.focus();
			return;
		}
		
		//第一个字符必须是字母
		if (!(trim(userIdField.value).charAt(0) >='a' && trim(userIdField.value).charAt(0) <='z')) {
			alert("用户代码首字符必须为字母!");
			userIdField.focus();
			return;
		}
		
		//采用正则表达式判断用户代码只能是数字或字母,为4~6位
		var re = new RegExp(/^[a-zA-Z0-9]{4,6}$/);
		if (!re.test(trim(userIdField.value))) {
			alert("用户代码必须为数字或字母,只能为4~6位!");
			userIdField.focus();
			return;
		}
		
		
		//用户名称必须输入,不能和用户代码不能为空一致
		if (trim(document.getElementById("userName").value).length == 0) {
			alert("用户名称不能为空!");
			document.getElementById("userName").focus();
			return;
		}
		
		//密码至少6位
		if (trim(document.getElementById("password").value).length < 6) {
			alert("密码至少6位!");
			document.getElementById("password").focus();
			return;
		}
		//如果联系电话不为空,进行判断,判断规则:都为数字,采用两种方式:1、采用正则,2、不采用正则
		var contactTelField = document.getElementById("contactTel");
		
		//不采用正则
		/*
		if (trim(contactTelField.value) != "") {
			
			for (var i=0; i<trim(contactTelField.value).length; i++) {
				var c = trim(contactTelField.value).charAt(i);
				if (!(c >= '0' && c <= '9')) {
					alert("电话号码不合法!");
					contactTelField.focus();
					return;
				}
			}
		}
		*/
		if (trim(contactTelField.value) != "") { 
			//采用正则
			re.compile(/^[0-9]*$/);
			if (!re.test(trim(contactTelField.value))) {
				alert("电话号码不合法!");
				contactTelField.focus();
				return;
			}	
		}
				
		//如果emial不能空,进行判断,判断规则:只要包含@即可,@最好不再最前面和最后面
		var emailField = document.getElementById("email");
		if (trim(emailField.value).length != 0) {
			var emailValue = trim(emailField.value);
			if ((emailValue.indexOf("@") == 0) || (emailValue.indexOf("@") == (emailValue.length - 1))) {
				alert("email地址不正确!");
				emailField.focus();
				return;				
			}
			if (emailValue.indexOf("@") < 0) {
				alert("email地址不正确!");
				emailField.focus();
				return;				
			}
		}
		//alert("a" + document.getElementById("spanUserId").innerHTML + "a");
		if (document.getElementById("spanUserId").innerHTML != "") {
			alert("用户代码已经存在!");
			userIdField.focus();
			return;
		}
		
		
		/* 	document.getElementById("userForm").action="user_add.jsp";
		document.getElementById("userForm").method="post";
		document.getElementById("userForm").submit(); */
		//等同上面的写法
		with (document.getElementById("userForm")){
			action="user_add.jsp";
			method="post";
			submit();
		}
	}
	
	function init() {
		document.getElementById("userId").focus();
	}
	
	function userIdOnKeyPress() {
		//alert(window.event.keyCode);
		if (!(event.keyCode >= 97 && event.keyCode <=122)) {
			event.keyCode = 0;
		}
	}
	
	document.onkeydown = function(event) {

		if (window.event.keyCode == 13
				&& window.event.srcElement.type != 'button') {
			window.event.keyCode = 9;
		}
	}

	function validate(field) {
		if (trim(field.value).length != 0) {
			var xmlHttp = null;
			//表示当前浏览器不是ie,如ns,firefox
			if(window.XMLHttpRequest) {
				xmlHttp = new XMLHttpRequest();
			} else if (window.ActiveXObject) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			var url = "user_validate.jsp?userId=" + trim(field.value) + "&time=" + new Date().getTime();
			
			//设置请求方式为GET,设置请求的URL,设置为异步提交
			xmlHttp.open("GET", url, true);
			
			//将方法地址复制给onreadystatechange属性
			//类似于电话号码
			xmlHttp.onreadystatechange=function() {
				//Ajax引擎状态为成功
				if (xmlHttp.readyState == 4) {
					//HTTP协议状态为成功
					if (xmlHttp.status == 200) {
						if (trim(xmlHttp.responseText) != "") {
							//alert(xmlHttp.responseText);
							document.getElementById("spanUserId").innerHTML = "<font color='red'>" + xmlHttp.responseText + "</font>"
						}else {
							document.getElementById("spanUserId").innerHTML = "";
						}
					}else {
						alert("请求失败,错误码=" + xmlHttp.status);
					}
				}
			};
			
			//将设置信息发送到Ajax引擎
			xmlHttp.send(null);
		} else {
			document.getElementById("spanUserId").innerHTML = "";
		}	
	}
</script>
	</head>

	<body class="body1" οnlοad="init()">
		<form name="userForm" target="_self" id="userForm">
			<input type="hidden" name="command" value="add">
			<div align="center">
				<table width="95%" border="0" cellspacing="2" cellpadding="2">
					<tr>
						<td> 
							
						</td>
					</tr>
				</table>
				<table width="95%" border="0" cellspacing="0" cellpadding="0"
					height="25">
					<tr>
						<td width="522" class="p1" height="25" nowrap>
							<img src="../images/mark_arrow_03.gif" width="14" height="14">
							 
							<b>系统管理>>用户维护>>添加</b>
						</td>
					</tr>
				</table>
				<hr width="97%" align="center" size=0>
				<table width="95%" border="0" cellpadding="0" cellspacing="0">
					<tr>
						<td width="22%" height="29">
							<div align="right">
								<font color="#FF0000">*</font>用户代码: 
							</div>
						</td>
						<td width="78%">
							<input name="userId" type="text" class="text1" id="userId"
								size="10" maxlength="10" οnkeypress="userIdOnKeyPress()" value="<%=userId %>" οnblur="validate(this)">
								<span id="spanUserId"></span>
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								<font color="#FF0000">*</font>用户名称: 
							</div>
						</td>
						<td>
							<input name="userName" type="text" class="text1" id="userName"
								size="20" maxlength="20" value="<%=userName %>">
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								<font color="#FF0000">*</font>密码: 
							</div>
						</td>
						<td>
							<label>
								<input name="password" type="password" class="text1"
									id="password" size="20" maxlength="20">
							</label>
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								联系电话: 
							</div>
						</td>
						<td>
							<input name="contactTel" type="text" class="text1"
								id="contactTel" size="20" maxlength="20" value="<%=contactTel %>">
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								email: 
							</div>
						</td>
						<td>
							<input name="email" type="text" class="text1" id="email"
								size="20" maxlength="20" value="<%=email %>">
						</td>
					</tr>
				</table>
				<hr width="97%" align="center" size=0>
				<div align="center">
					<input name="btnAdd" class="button1" type="button" id="btnAdd"
						value="添加" onClick="addUser()">
					    
					<input name="btnBack" class="button1" type="button" id="btnBack"
						value="返回" onClick="goBack()" />
				</div>
			</div>
		</form>
	</body>
</html>
</span>

         小结:之前学习Ajax总是迷迷糊糊的,这次感觉有清晰了不少,学习就是这样在原来的基础上i+1,总结一下就清楚了些,Ajax和之前相比就是多了Ajax引擎作为中介,浏览器与Ajax引擎交互,Ajax引擎与tomcat服务器交互,通过XMLHttpRequest对象传送一些信息,发送出去给tomcat,再接收回来给浏览器。


以上纯属个人见解,有不对的地方欢迎指正。




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值