Checking if user exists jquery validator,ajax and codeigneter
我试图检查用户名是否存在,但即使用户名不存在,它仍然说"用户名已存在"这是我的javascript代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | $.validator.addMethod("checkUsername", function(value, element) { var test =""; $.ajax({ type:"GET", url: site_url +"/ajax/checkusername/" + value, success: function(result){ if(result=="exists") return false; else return true; } }); }, "Username Already Exists." ); $("#myform").validate({ rules: { username2: { required: true, minlength: 6, checkUsername:true }, password2: { required: true, minlength: 6 }, email: { required: true, email: true } } }); }); |
这是我的控制器代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function checkusername($username) { $this->load->model('user_model'); $user = $this->user_model->getUser($username); if($user == null) { echo json_encode("notexists"); } else { echo json_encode("exists"); } } |
关于如何解决这个问题的任何想法?
提前致谢。
当您不使用
当你这么做时会发生什么?:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function checkusername($username) { $this->load->model('user_model'); $user = $this->user_model->getUser($username); if($user == null) { echo"notexists"; } else { echo"exists"; } } |
编辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.validator.addMethod("checkUsername", function(value, element) { var result = false; $.ajax({ type:"GET", async: false, url: site_url +"/ajax/checkusername/" + value, success: function(msg) { result = (msg =="exists") ? false : true; } }); return result; }, "Username Already Exists." ); |
您可以使用
1 2 3 | $.getJSON( site_url +"/ajax/checkusername/" + value, function( json ) { if(json=="notexists"){alert('Not exists')} }); |
或者将
1 | if($.parseJSON(result)=="exists") |
更新:我不得不改变我的答案
您的函数不会返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.validator.addMethod("checkUsername", function(value, element) { var test = false; $.ajax({ type:"GET", async: false, url: site_url +"/ajax/checkusername/" + value, success: function(result){ if(result=="notexists") {test = true; } } }); return test; }, "Username Already Exists." ); |