用户名使用Ajax PHP进行实时检查

时间:2012-09-13 06:30:44

标签: php jquery

我有一个代码,其中有一个函数可以检查用户名是否可用。

我对此功能的运作方式感到困惑。

JS:

jQuery(document).ready(function(){
    // binds form submission and fields to the validation engine
    jQuery("#register-form").validationEngine();
});

HTML输入:

<form action="" id="register-form">
    <input value="" class="validate[required,custom[onlyLetterNumber],maxSize[20],ajax[ajaxNameCallPhp]]] input" type="text" name="username"/>
</form>

这是我的JS功能:

(function($){
    $.fn.validationEngineLanguage = function(){};
    $.validationEngineLanguage = {
        newLang: function(){
            $.validationEngineLanguage.allRules = {

                "ajaxNameCallPhp": {
                    // remote json service location
                    "url": "ajaxNameCallPhp.php",
                    // error
                    "alertText": "* This name is already taken",
                    // speaks by itself
                    "alertTextLoad": "* Validating, please wait"
                }
            };
        }
    };

    $.validationEngineLanguage.newLang();
})(jQuery);

这是我的ajaxNameCallPhp.php功能:

include ("config.php");
$username = trim(strtolower($_POST['username']));
$username = mysql_escape_string($username);

$query = "SELECT username FROM user WHERE username = '$username' LIMIT 1";
$result = mysql_query($query);
$num = mysql_num_rows($result);

echo $num;
mysql_close();

所以任何人都可以给我一个解决方案吗?

我很感激并感谢你的关注。

谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个

function UserNameExist(){ 
    $("#msg").html( "* Validating, please wait" );
    $.ajax({
      url: "ajaxNameCallPhp.php",
      type: "POST",
      data: {username : $('#username').val()},
      dataType: "html"
    }).done(function(msg) {
      if(msg > 0){
        $("#msg").html( "* This name is available" );
      }else{
        $("#msg").html( "* This name is already taken" );
      }
    });
   }

其中#msg是您显示按摩的div的ID

和#userName是文本框的ID

希望有所帮助。