gpt4 book ai didi

php - ajax调用检查重复数据

转载 作者:行者123 更新时间:2023-12-01 02:46:27 24 4
gpt4 key购买 nike

这是让ajax检查用户是否存在的表单。

<!DOCTYPE html>

<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>

这是 userexists.php 模块

<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");

$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{

}
?>

但是我一直想真正弄清楚ajax功能实际上是如何工作的,例如,在我知道输入的用户名已被使用后,我应该在空白字段中输入什么?我根本不懂ajax。

[更新]谢谢,我现在明白了,我有几个答案,不知道该选哪一个作为最佳答案。没有选择全部的选项。

最佳答案

您的代码中有很多错误,请尝试以下代码:

<!DOCTYPE html>

<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>

对于你的 php 代码:

<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");

$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());

$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection

$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations

$query = mysql_query($sql);

if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>

关于php - ajax调用检查重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10362430/

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