我想在用户注册时检查用户名的可用性。我在前端工作。后端代码给了我。
这些是 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 OR INVALID_USERNAME OR USERNAME_EXISTS。请帮助我。