我阅读了关于jQuery验证器的回复,其中概述了一个方法来检查数据库中的值的用户名。
Ive尝试实现这个方法,但无论从PHP文件返回什么,我总是得到消息,用户名已被采取。
$.validator.addMethod("uniqueUserName",function(value,element) { $.ajax({ type: "POST",url: "PHP/get_save_status.PHP",data: "checkUsername="+value,dataType:"html",success: function(msg) { // if the user exists,it returns a string "true" if(msg == "true") return false; // already exists return true; // username is free to use } })},"Username is Already Taken");
这里是验证代码…
username: { required: true,uniqueUserName: true },
有一个特定的方式,我应该从PHP返回的消息。
谢谢
一个
解决方法
您正在执行AJAX请求,ergo:当您的自定义验证器返回true或false时,验证已完成工作。
您将需要使用异步。另见这篇文章:How can I get jQuery to perform a synchronous,rather than asynchronous,Ajax request?
就像是:
function myValidator() { var isSuccess = false; $.ajax({ url: "",data: {},async: false,success: function(msg) { isSuccess = msg === "true" ? true : false } }); return isSuccess; }
警告:
As of jQuery 1.8,the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().