Ajax-验证码

       function validateCode(){
 	 var code=document.getElementById("code").value;
	 var spanObj=document.getElementById("codeMsg");
	 if(code==null || code==''){
		 spanObj.innerHTML="<font color='red'>code not null</font>";
	 }else{
		 //验证码不为null,采用Ajax进行异步验证
		 var xmlHttpRequest=new XMLHttpRequest();
		 xmlHttpRequest.open("post","MemberServlet/checkCode?code="+code);
		 xmlHttpRequest.send(null);
		 //回调函数:接收返回的数据
		 xmlHttpRequest.onreadystatechange=function(){
			 if(xmlHttpRequest.readyState==4){
				 if(xmlHttpRequest.status==200){
					 if(xmlHttpRequest.responseText=="true"){
						 checkCode=true;//用于验证表单整体提交(不能调用函数直接验证)
spanObj.innerHTML="<font color='green'>code right!</font>"; }else{ //验证码输入错误后,应该重新加载验证码 reloadCode(); spanObj.innerHTML="<font color='red'>code wrong!</font>"; } }else{ spanObj.innerHTML="<font color='red'>code error!!</font>"; } } } } }

  

  
//重新加载验证码 
function reloadCode(){
   //需要在img标签添加一个id属性:为了获取其src属性
   var codeImg=document.getElementById("codeId");
   //需要在src后面添加一个随机变动的数:确保提交的路径不是同一个
   codeImg.src="image.jsp?p="+Math.random();
 }
 

注意:

1.重写加载验证码需要在src路径后添加随机变化的数:保证提交路径不是同一个;

2.验证整体表单提交的时候,不能直接调用含有ajax异步处理的方法的返回结果,而是采用一个变量来完成验证操作;

 

posted @ 2017-10-24 09:26  scwyfy  阅读(181)  评论(0编辑  收藏  举报