0

シンプルなログインフォームに JavaScript 検証を使用しようとしています。現在、ユーザー名の入力に焦点を当てています(ユーザー名が既に使用されている場合は、赤で表示され、その下に「そのユーザー名は既に使用されています」というエラーが表示されます)。ただし、要素ネットワークを調べたときに、入力が registerjs.php ファイルに送られていることがわかりましたが、入力が変更されても何も表示されません

私が持っているHTMLフォームページの頭に

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    function valusername() {
    var username = $('input#username').val();
    if ($.trim(username) != '') {
        $.post('../ajax/registerjs.php', {username: username}, function(data) {
        if (data == 'That username is already taken') {

        document.getElementById("username").style.border="3px solid red";
        $('div#username_error').text(data);
    }

    });
    }
}

</script>

実際のテキスト入力は

<input class="input" type="text" tabindex="1" placeholder="Username*" 
style="height:20px;" name="username" id="username" onchange="valusername()">
<div id="username_error"></div>

リンクされているphpファイルregisterjs.phpはうまくいくと確信しています

<?php
include('../init.php');
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
$username = $_POST['username'];
if (user_exists($username) === true) {
echo("
    That username is already taken
    ");
} else {
echo("Good");
}
}
?>

なぜ私がこの問題を抱えているのか誰か知っていますか? スクリプトのif文のようです。

4

2 に答える 2

2

これを行う :

function valusername() 
{
    var username = $('input#username').val();
    if ($.trim(username) != '') 
    {
        $.post('../ajax/registerjs.php', {username: username}, function(data) 
        {
            if ($.trim(data) == 'That username is already taken') 
            {
                document.getElementById("username").style.border="3px solid red";
                $('div#username_error').text(data);
            }
        });
    }
}
于 2013-01-03T05:03:22.297 に答える
1

より良いアプローチ:

<input class="input" type="text" tabindex="1" placeholder="Username*" 
style="height:20px;" name="username" id="username" >
<div id="username_error"></div>

JS

<script>
    $(function(){
    $(document).on('change paste','#username', function () {
        var username = $(this).val();
        if ($.trim(username) !== '') {
            $.post('../ajax/registerjs.php', {username: username},
                function(data){
                    if (data) {
                        $("#username").css({'border','3px solid red'});
                        $('div#username_error').text('Username already exist');
                        return false;
                    }
                }
            ); // end of $.post
        } // end of if
    })
})
</script>

registerjs.php

<?php
include('../init.php');
// here i assume user_exists return true or false
if ( !empty($_POST['username']) && user_exists($username)) {
 return TRUE;
} 
else{
  return FALSE;
}
?>
于 2013-01-03T05:14:31.520 に答える