我們在做驗證碼的時候往往由于要反作弊,驗證有時故意加入多的干擾因素,這時驗證碼顯示不很清楚,用戶經常輸入錯誤。這樣不但要重新刷新頁面,導致用戶沒有看清楚驗證碼而重填而不是修改,而且如果沒有用session保存下用戶輸入的其它數據的話(如姓名),用戶剛剛輸入的內容也不存在了,這樣給用戶造成不好的體驗。
本例在原有驗證方式基礎之上增加一段js,通過xmlhttp來獲取返回值,以此來驗證是否有效,這樣即使用戶瀏覽器不支持js,也不會影響他的正常使用了。
為了防止作弊,當用戶連接3次輸入錯誤時則重載一下圖片,這樣也利于用戶因為圖片上的驗證碼辨認不清而使終無法輸入正確?!?/p>
本例還特別適合檢驗用戶名是否有效,只要從后臺做個sql查詢,返回一個值或是xml即可。(這種例子太多,就在此不贅述了)。
本例的優點在于非常方便用戶輸入,而且減少對服務器端的請求,可以說既改善用戶體驗而且略會節省帶寬成本,但相應地要在頁面上增加一段javascript代碼,在目前網速越來越快人們要求便捷舒適的 今天,似乎我們更應注意提供給用戶良好的使用感受?!?/p>
代碼如下,
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());
}
新聞熱點
疑難解答