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异步处理的方法的返回结果,而是采用一个变量来完成验证操作;

 

转载于:https://www.cnblogs.com/yuefeng123/p/7721923.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值