gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:00:42 25 4
gpt4 key购买 nike

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

最佳答案

如果您熟悉 JS/Ajax 基础知识,这实际上还不错。

您基本上需要从注册页面调用 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 对象,并将用户名变量传递给 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 和 ajax 中创建一个注册页面,在不刷新页面的情况下检查某个用户名是否已经存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4215233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com