解決使用Validform插件,datatype裏用ajax驗證數據是否已經存在時出現的問題

       這幾天寫項目的時候,後臺引用了一個網上的模版文件,而模版文件中,對與表單的驗證,恰好使用了Validform這個插件,對於這種插件,我不得不說,好用是好用,就是坑太多,一不小心掉進去,就很難受了,百度了半天也不一定有好的結果。

       這不,今天下午,我就掉到了坑裏,各種調試,各種百度,浪費了我大量的時間才搞定。其實我覺得吧,表單驗證那麼簡單的問題,沒必要費那麼大力氣,我大概是運氣不好,百度了很多都沒有得到完美的解釋,根據正常的邏輯來,又因爲Validform本身存在的坑無法繞過,所以我寫這篇博客,以示後來者,希望遇到相同或者相似問題的人能看到這篇文章,節約時間。

      先說說問題:

 這是一個input框,我想先驗證字符長度是否符合條件,再驗證輸入的用戶名是不是在數據庫已存在,若是存在則提示相應文字,若不存在則通過:


       代碼:

 <input type="text" class="input-text col-xs-12" value="" placeholder=""  id="user-name" name="username" datatype="username" nullmsg="用戶名不能爲空" errormsg="用戶名爲2到16位字符">
     可以看到我給datatype命名爲username,根據Validform插件的規則 ,下面的js我是這樣寫的:

     錯誤的示範1:

datatype:{
			 username:function(gets,obj,curform,regxp){ 
				var reg = /^\w{2,16}$/;
				if(!reg.test(gets)) {
					return false; 
				}
				//驗證用戶名是否存在
				$.ajax({
					url:"doAdminGetAction.php?act=checkAdminExist",
					data:{"username":gets},
					dataType:'json',
					type:'post',
					success:function(data){
						if(data.status == 0){
							console.log(data.info)
							return "此用戶已存在";
						}else{
							console.log(data.info)
							return true;
						}
				
						},
					error:function(data){
						console.log(data);
						}
				});	
			  }
			 },


     在這裏我首先申明:我的後臺驗證是沒有問題的,我在ajax的success裏打印了後臺傳過來的數據,都是正確的。
     但並沒有什麼卵用,本來根據Validform的使用規則,如果我return true則證明驗證通過,我return false或者任意字段則證明驗證不成功,會提示默認信息(input標籤內errormsg裏的值)或者提示的我編寫的任意字段。但是經過實驗,每次驗證除了在控制檯打印驗證的正確信息,Validform本身並沒有對我在success裏做的操作有任何反應

   香菇藍瘦,經過一番百度,我發現網上別人的解決方案沒有在ajax的success裏做直接的return true或者false或者是返回字符串的操作,都是在ajax外面做了return的操作,所以根據這個提示,我將代碼改進成這樣:
     

 錯誤的示範2:

datatype:{
			 username:function(gets,obj,curform,regxp){ 
				var reg = /^\w{2,16}$/;
				if(!reg.test(gets)) {
					return false; 
				}
				//驗證用戶名是否存在
				var result;
				$.ajax({
					url:"doAdminGetAction.php?act=checkAdminExist",
					data:{"username":gets},
					dataType:'json',
					type:'post',
					success:function(data){
						if(data.status == 0){
							console.log(data.info)
							result = data.info;
						}else{
							console.log(data.info)
							result = true;
						}
				
						},
					error:function(data){
						console.log(data);
						}
				});
			   console.log(data);
				return result;
				
			  }
			 },


    結果還是沒卵用,測試結果跟之前一模一樣,用戶名的重複驗證形同虛設,輸入數據庫中已存在的用戶名,會在控制檯打印出“用戶名已存在的信息”,但表單驗證依然是通過的,很無奈,我在ajax裏將result賦值,return result之前打印了result,結果 result的值竟然是undefine!!!!

     這個意思就是ajax中success裏對result的賦值是沒用的,程序直接跳過了ajax的驗證,將結果返回給了Validform進行處理,
這是爲什麼呢?大家都知道ajax是異步提交,而與後臺交互獲取數據是需要時間的,這個時間遠多餘程序執行的時間,所以就會出現result跳過ajax的賦值,直接返回給插件,所以只需在ajax里加入
                                 async:false,
加上這個條件,則執行ajax時,會停掉除ajax外的所有程序,這樣就能在result進行正確的賦值後再返回給插件處理。
因此,根據這個,我將代碼修改成這樣:

 正確的示範:

 datatype:{
			 username:function(gets,obj,curform,regxp){ 
				var reg = /^\w{2,16}$/;
				if(!reg.test(gets)) {
					return false; 
				}
				//驗證用戶名是否存在
				var result;
				$.ajax({
					url:"doAdminGetAction.php?act=checkAdminExist",
					data:{"username":gets},
					dataType:'json',
					type:'post',
					async:false,
					success:function(data){
						if(data.status == 0){
							console.log(data.info)
							result = data.info;
						}else{
							console.log(data.info)
							result = true;
						}
				
						},
					error:function(data){
						console.log(data);
						}
				});
			
				return result;
				
			  }
			 },
   運行一下,ok!
所以,總結一下就兩點:
1. return true 或者 false  或者返回字符串,要寫在ajax外面
2.ajax一定要加上async:false,   因爲ajax默認這個的值爲true



附上完整的前後端代碼:
前端js:
//表單驗證提交
$("#form-admin-add").Validform({		
		 tiptype:2,
		 tipSweep:false,
		 submitForm:true,
		 ignoreHidden:true,
		 postonce:true,   
		 ajaxPost:true,
		 datatype:{
			 username:function(gets,obj,curform,regxp){ 
				var reg = /^\w{2,16}$/;
				if(!reg.test(gets)) {
					return false; 
				}
				//驗證用戶名是否存在
				var result;
				$.ajax({
					url:"doAdminGetAction.php?act=checkAdminExist",
					data:{"username":gets},
					dataType:'json',
					type:'post',
					async:false,
					success:function(data){
						if(data.status == 0){
							console.log(data.info)
							result = data.info;
						}else{
							console.log(data.info)
							result = true;
						}
				
						},
					error:function(data){
						console.log(data);
						}
				});
			
				return result;
				
			  }
			 },
		callback:function(data){
			console.log(data);
		//form[0].submit();
		if(data.status==1){ 
                layer.msg(data.info, {icon: data.status,time: 1000}, function(){  
                    location.reload();//刷新頁面 
                    });   
            }else if(data.status==3){
            	layer.msg(data.info, {icon: data.status,time: 1000}); 
            }else{ 
                layer.msg(data.info, {icon: data.status,time: 3000}); 
            } 		  
			var index =parent.$("#iframe").attr("src");
			parent.layer.close(index);
			//
		}				
	});
後端代碼:
if($act == 'checkAdminExist'){
    $username = $_POST['username'];
    $sql = "select id from shiguang_admin where username='{$username}'";
    $rows = fetchOne($link,$sql);//獲取是否有這個用戶
    if($rows){
        echo ajaxReturn(0, "此管理員名已存在");
    }else{
        echo ajaxReturn(1, "此管理員名可用");
    }
}
/**
 * 返回ajax需求的數據
 * @param int $status
 * @param char $msg
 * @param string/array $data
 * @param string $type
 * @return string  所需格式字符串
 */
function ajaxReturn($status,$msg,$data=null,$type="json"){
    $res = [
        'info'=>$msg,
        'status'=>$status,
        'data'=>$data
    ];
    if($type == "json"){
        header('Content-type: application/json');
        return json_encode($res);
    }else if($type == "xml"){
        header('Content-Type:text/xml; charset=utf-8');
        return arrayToXml($res);
    }else{
        exit("無此數據格式");
    }
    
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章