首页 > 编程 > JSP > 正文

AJAX+jsp无刷新验证码实例

2024-09-05 00:20:40
字体:
来源:转载
供稿:网友

  我们在做验证码的时候往往由于要反作弊,验证有时故意加入多的干扰因素,这时验证码显示不很清楚,用户经常输入错误。这样不但要重新刷新页面,导致用户没有看清楚验证码而重填而不是修改,而且如果没有用session保存下用户输入的其它数据的话(如姓名),用户刚刚输入的内容也不存在了,这样给用户造成不好的体验。 

  本例在原有验证方式基础之上增加一段js,通过xmlhttp来获取返回值,以此来验证是否有效,这样即使用户浏览器不支持js,也不会影响他的正常使用了。 

  为了防止作弊,当用户连接3次输入错误时则重载一下图片,这样也利于用户因为图片上的验证码辨认不清而使终无法输入正确。 

  本例还特别适合检验用户名是否有效,只要从后台做个sql查询,返回一个值或是xml即可。(这种例子太多,就在此不赘述了)。 

  本例的优点在于非常方便用户输入,而且减少对服务器端的请求,可以说既改善用户体验而且略会节省带宽成本,但相应地要在页面上增加一段javascript代码,在目前网速越来越快人们要求便捷舒适的 今天,似乎我们更应注意提供给用户良好的使用感受。 

  代码如下,

  4,net.js,封装好的xmlhttp对象,可以很方便的调用

/*namespacingobject*/
varnet=newobject();
 
net.ready_state_uninitialized=0;
net.ready_state_loading=1;
net.ready_state_loaded=2;
net.ready_state_interactive=3;
net.ready_state_complete=4;
/*---contentloaderobjectforcross-browserrequests---*/
net.contentloader=function(url,on_load,on_error,method,params,contenttype){
 this.req=null;
 this.on_load=on_load;
 this.on_error=(on_error)?on_error:this.defaulterror;
 this.loadxmldoc(url,method,params,contenttype);
}
net.contentloader.prototype.loadxmldoc=function(url,method,params,contenttype){
 if(!method)
 {
method="get";
 }
 if(!contenttype&&method=="post")
 {
contenttype='application/x-www-form-urlencoded';
 }
 if(window.xmlhttprequest)
 {
this.req=newxmlhttprequest();
 }
 elseif(window.activexobject)
 {
 //addtrycatch;
 try{
   this.req=newactivexobject("msxml2.xmlhttp");
 }catch(e1){
  try{
   this.req=newactivexobject("microsoft.xmlhttp");   
   }catch(e2){
  }
 }
  //
//this.req=newactivexobject("microsoft.xmlhttp");
 }
 if(this.req)
 {
try
{
 varloader=this;
 this.req.onreadystatechange=function()
 {
 net.contentloader.onreadystate.call(loader);
 }
 this.req.open(method,url,true);
 if(contenttype)
 {
  this.req.setrequestheader('content-type',contenttype);
 }
 this.req.send(params);
}
catch(err)
{
 this.on_error.call(this);
}
 }
}
net.contentloader.onreadystate=function(){
 varreq=this.req;
 varready=req.readystate;
 if(ready==net.ready_state_complete){
varhttpstatus=req.status;
if(httpstatus==200||httpstatus==0){
 this.on_load.call(this);
}else{
 this.on_error.call(this);
}
 }
}
net.contentloader.prototype.defaulterror=function(){
 alert("errorfetchingdata!"
+"nnreadystate:"+this.req.readystate
+"nstatus:"+this.req.status
+"nheaders:"+this.req.getallresponseheaders());
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表