是否可以在“输入”的 evnentListener 中使用 $.ajax

问题描述 投票:0回答:1

-这是我的javascript:

let uname = document.getElementsByClassName('login-username')\[0\];

let pass = document.getElementsByClassName('login-password')\[0\];
uname.addEventListener('input', function(){

        if(uname.value.length > 0){
            $('.login-username').addClass('is-valid');
    
            $.ajax({
                url: '__login_backend.php',
                method: "POST",
                async: false,
                dataType: "html",
                data:{
                "unameCheck":1,
                "username":uname
                },
                success:function(unameCheck){
                    alert(unameCheck);
                    if(unameCheck == 'USERNAME_VALID'){
                     ** STYLE INPUT FIELD **
                    } else {
                     ** STYLE INPUT FIELD **
                    }
                }
            });
        }else{
            $('.login-username').removeClass('is-valid');
        }
    })

-这是我的 HTML

<label for="username" class="d-none">Username</label>
<input type="text" id="username" class="form-input login-username" name="username" pattern="[a-zA-Z]*" placeholder="Username">
                                
<label for="password" class="d-none">Password</label>
<input type="password" id="password" class="form-input login-password" name="password" placeholder="Password">
<input type="submit" class="form-input login-btn" name="login-btn" value="Login" > 

-这是 PHP

if(isset($_POST['unameCheck'])){

    $username = $_POST['uname'];

    $q = "SELECT uname FROM table WHERE uname = '$username'";
    $result = @mysqli_query($dbcon, $q);
    if($result){
        echo 'USERNAME_VALID';
    }else{
        echo 'USERNAME_INVALID';
    }
}

此代码使浏览器不断崩溃, 是否可以运行此代码?

我在期待;在用户输入时,它会检查 MySQL 数据库中的用户名是否匹配,如果有匹配项 它为输入字段设置样式

还是我离题太远了?

javascript html ajax addeventlistener
1个回答
0
投票

我将我的代码更改为:- 它有效

Javscript:

$('.login-username').on('input', function(){
    let username = $(this).val();
    // alert(input)

    if(username!= ''){
        $.ajax({
            url:'__login_backend.php',
            method:'POST',
            data:{username:username},
            success:function(ckUsr){
                // alert(ckUsr);
                if(ckUsr === 'USERNAME'){
                    $('.login-username').addClass('is-valid');
                }
            }
        });
    }
})

PHP:

if(isset($_POST['input'])){
$uname= $_POST['username'];

$q = "SELECT * FROM table WHERE username = '$uname'";
$result = @mysqli_query($dbcon, $q);
if(mysqli_num_rows($result) == 1){
    echo 'USERNAME';
}

}

© www.soinside.com 2019 - 2024. All rights reserved.