我想在用户注册时检查用户名可用性。我在前端工作。后端代码是给我的。
这些是signup.php中的php代码
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
现在我不知道那么多的PHP。我创建了一个javascript函数来将用户名发送到signup.php页面进行验证。
这是我的功能
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
这里我得到x的值为[object Object]。 但我需要将返回消息存储在变量x中。我想知道它是NULL_USERNAME还是INVALID_USERNAME或USERNAME_EXISTS。请帮助我。
答案 0 :(得分:2)
尝试,
function(data){
var x = data.E_UserName;
}, "json");
还会根据MrCode's answer
将您的请求更改为 GETfunction submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}
答案 1 :(得分:2)
用户名已发布,但在PHP中,您尝试使用$_GET
访问该用户名,请更改为:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
此外,您的验证逻辑看起来不正确,如果用户名有效且可用,该怎么办?我会添加一个else子句并设置一个success
变量:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
和ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}