如何在php和ajax中创建一个注册页面,它会在不刷新页面的情况下检查某个用户名是否已经存在? - php

我有一个register.php文件,它为我的网站创建了新用户。但是,如果某人使用已经存在的用户名,则仅当他输入整个表单并提交时才会生成错误。如何实现Ajax / Jquery以在不提交表单的情况下显示它?

参考方案

如果您熟悉JS / Ajax Basics,实际上还不错。

您基本上需要从注册页面调用javascript函数。

注册表格上的HTML

<!--This is the textbox with the value we are checking-->
<!--onkeyup can be substituted by any other event you wish to use intead-->
<input onkeyup="checkUsername(this.value);" name="username" id="username" />

<!--This is where we'll display the response-->
<div id="response"></div>

该JS函数将创建一个ajax对象,并将username变量传递给PHP页面进行处理,并等待响应...

的JavaScript

function checkUsername(username){

    //Construct the url, passing the username to the PHP page
    var url= 'checkNameAvailability.php?username=' + encodeURIComponent(username);

    if (ajax.readyState == 4 || ajax.readyState == 0) {
        ajax.open("POST", url, true);
        ajax.onreadystatechange = function (){
            if (ajax.readyState == 4) {    

                //When you get the result from the PHP, put it in the response div
                document.getElementById('response').innerHTML=ajax.responseText;
            }
        }; 
        ajax.send(null);
    }
}

//Just copy and paste this function - don't change it at all.
function getXmlObject() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            showError('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.','Please Wait');
        }
    }

然后,PHP页面获取用户名变量,以所需的任何方式(可用,足够长,是否具有无效字符,是否不合适等)对其进行处理,并返回响应。

checkNameAvailability.php

<?php

    //Accept a variable called 'username' that we are checking.
    $username=$_REQUEST['username'];

    //Run Checks to see if username is valid
    if ($username=="Dutchie") 
            die ("Username is reserved or already taken");
    if (strlen($username)<5) 
            die("The username is too short.");

   die("Username is Valid");

?>

PHP:获取调用引用的数组名称 - php

假定以下函数并调用:function doSomething( &$someArray ) { // Do something to $someArray } $names=array("John", "Paul", "George", "Ringo"); doSomet…

jQuery Ajax PHP重定向到另一个页面 - php

JavaScript文件:$.ajax({ type: "POST", url: "ajax.php", data: dataString, success: function(r) { $("#div").html(r); } }); 我想在成功的情况下将页面重定向到new.php,所以在我使用a…

PHP-MySQL结果转换为JSON - php

我试图了解如何将MySQL结果转换为JSON格式,以便以后可以在Javascript中使用此JSON来构建HTML表。但是我的代码只是产生大量的空值,我还不明白为什么。$result = mysqli_query($con, "SELECT * FROM Customers"); $test = json_encode($result);…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP-将日期插入日期时间字段 - php

我已在数据库中使用datetime字段存储日期,使用PHP将“今天的日期”插入该字段的正确方法是什么?干杯, 参考方案 我认为您可以使用php date()函数