javascript 如何在不发布表单的情况下检查表单中的重复用户名,如果用户名已经存在,如何将焦点设置在用户名上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13700342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:31:47  来源:igfitidea点击:

How can I check duplicate username in a form without posting form and set focus on username if it already exists?

phpjavascriptajaxhtml

提问by Naeem Shakir

I have a form to filled out by user. Its user registration form. I want that when user fill username text,my form should search for user name whether it exist or not.If it exist then username text field should get focus.My database table name is users and it contains column named as id,username,password,status. Here is my code.

我有一个表格需要用户填写。其用户注册表。我希望当用户填写用户名文本时,我的表单应该搜索用户名是否存在。如果存在,则用户名文本字段应该获得焦点。我的数据库表名是用户,它包含名为 id、用户名、密码的列,地位。这是我的代码。

<form name="user" action="#" method="post">
    <label>Username</label>
    <input type="text" maxlength="25" name="username" />
    /*here i want to check from my db table weather username exists or not*/
    <label>Password</label>
    <input type="password" maxlength="25" name="password" />
    <input type="submit" value="Submit" />
</form>

I can do it when user submits the form.But my requirement is to check value with out submitting form and username should get focus. and in php I have following code

我可以在用户提交表单时执行此操作。但我的要求是在不提交表单的情况下检查值,并且用户名应该得到关注。在 php 中我有以下代码

<?php
    mysql_connect("localhost","root","") or die(mysql_error());

    mysql_select_db("test") or die(mysql_error());
    $username = $_REQUEST['username'];
    $query=mysql_query("SELECT * from user where name='$username'");
    $row=mysql_num_rows($query);
    if($row==1){
        echo "true";
    } else {
        echo "false";
    }
?>

回答by Rodrigo Neves

Make an ajax request to a server side script of yours that does the check on the database and returns something you can intepret. Then act on it on the ajax success response (focusing the field).

向您的服务器端脚本发出 ajax 请求,该脚本对数据库进行检查并返回您可以解释的内容。然后对 ajax 成功响应采取行动(关注领域)。

There are thousands of examples of this online. Check @danish hashmi 's example ( http://blog.webwizo.com/2011/06/03/check-username-availability-in-php-with-jquery-ajax/) or google it for more.

网上有成千上万个这样的例子。检查@danish hashmi 的例子(http://blog.webwizo.com/2011/06/03/check-username-availability-in-php-with-jquery-ajax/)或谷歌搜索更多。

回答by arun

Html Form

html格式

<form method="post" action="register.php">
    ......
    <label for="username">Username</label>
    <input type="text" maxlength="25" name="username" id="username">
    ......
</form>

Js

JS

<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
    $('#username').keyup(check_username); //use keyup,blur, or change
});
function check_username(){
    var username = $('#username').val();
    jQuery.ajax({
            type: 'POST',
            url: 'check_username.php',
            data: 'username='+ username,
            cache: false,
            success: function(response){
                if(response == 0){
                   alert('available')
                }
                else {
                     alert('not available')
                     //do perform other actions like displaying error messages etc.,
                }
            }
        });
}
</script>

write your table user name checking in check_username.php, the response from this php is count of rows with the provided username,something like below

写入您的表用户名签入check_username.php,此 php 的响应是提供用户名的行数,如下所示

<?php
    /*** mysql hostname ***/
    $hostname = 'localhost';

    /*** mysql username ***/
    $username = 'username';

    /*** mysql password ***/
    $password = 'password';

    /*** mysql databse ***/
    $dbname = 'database';

    try 
    {
        $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
        /*** echo a message saying we have connected ***/
        //echo 'Connected to database';
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }   

    $stmt = $dbh->prepare("SELECT * FROM user where name = ?");
    $stmt->execute(array($_POST['username']));
    echo $stmt->rowCount();
?>

回答by Elmor

I'm thinking of you binding checking for existence of user on keyup event of your name="username" field (should give an id to that). do you use jquery or any other library for js?
It would be much simpler to achieve what you're planning to do with using libraries.

我在想你在你的 name="username" 字段的 keyup 事件上绑定检查用户的存在(应该给它一个 id)。你使用 jquery 或任何其他 js 库吗?
使用库来实现您计划做的事情会简单得多。

回答by Dipesh Parmar

To do so you can set textbox on change event and pass textbox value to ajax call like below.
input type="text" id="username"

为此,您可以在更改事件上设置文本框,并将文本框值传递给 ajax 调用,如下所示。
input type="text" id="username"

Now in js file add below code.

现在在js文件中添加以下代码。


$(document).ready(function(){
  $(#username).change(function(e)
  {
    e.preventDefault();
    $.ajax({
       url : 'youphpfile.php?username='+$(#username).val();,
//or $(#username).attr('value') dataType: 'json', success : function() {} }); }); });

now in youphpfile.php file do checking for sended username parameter.

现在在 youphpfile.php 文件中检查发送的用户名参数。

$username = $_REQUEST['username']; // $_GET['username']; get will be good for faster response.

$username = $_REQUEST['username']; // $_GET['username']; get will be good for faster response.

mysql_connect

mysql_connect

and check username

and check username

And you done. Cheers.

你完成了。干杯。

回答by Maloric

You will probably need a web service to check if the username exists and when the username field loses focus, make an ajax call to the service using jQuery.

您可能需要一个 Web 服务来检查用户名是否存在,并且当用户名字段失去焦点时,使用 jQuery 对服务进行 ajax 调用。

$(document).ready(function(){
    $('input[name="username"]').blur(function(){
        var txt = $(this);
        var username = txt.val();
        $.ajax({
            type: "POST",
            url: "myUsernameService.php",
            data: { uname: username }
        }).done(function(res) {
            if (res == "false"){
                txt.removeClass("valid").addClass("invalid");
            } else {
                txt.removeClass("invalid").addClass("valid");
            }
        });
    });
});

I wouldn't suggest focusing on the username textbox again as the AJAX call can take a couple of seconds to return a value, at which point the user might be busy typing in another field.

我不建议再次关注用户名文本框,因为 AJAX 调用可能需要几秒钟才能返回一个值,此时用户可能正忙于在另一个字段中输入。

The above code assumes that you have a method on "myUsernameService.php" that accepts one variable called "uname" and returns a string of "true" or "false".

上面的代码假设您在“myUsernameService.php”上有一个方法,它接受一个名为“uname”的变量并返回一个字符串“true”或“false”。