我正在尝试创建用户名可用性检查。我似乎没有得到回应。我在控制台中没有出现任何错误,只有200 OK但没有响应,这应该是$ result?
PHP:
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$result='user found';
}else{
$result='user not found';
}
echo $result;
}
jquery的:
$.post('username_check.php', { signusername: username }, function (result)//not getting this back
{
if (result == 'user not found')
{
$('.error').text('Avaliable');
} else if (result == 'user found')
{
$('.error').text('Taken');
}
});
如果我将'else if'更改为'else',它将起作用并显示'take',如果我更改result =''它仍然无效。
任何人都知道我做错了什么?
编辑 -
function checkUsername($signusername, $conn) {
$stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
$stmt->bindParam(1, $signusername);
$stmt->execute();
if($stmt->rowCount() == 1) {
return TRUE;
}
};
这是检查用户名的功能,我也用它来检查表单提交后是否取得用户名,它运行正常。也许问题出在这个功能上?
答案 0 :(得分:1)
PHP:
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$found = true;
} else {
$found = false;
}
echo json_encode(array('userFound' => $found));
}
JS:
$.post('username_check.php', { signusername: username }, function (data) {
if (data.userFound == false) {
$('.error').text('Avaliable');
} else if (data.userFound == true) {
$('.error').text('Taken');
} else {
$('.error').text('Error checking for username avaliablility');
}
}, 'json')
.error(function(e){
console.log(e); // Look at your JS console for more info
$('.error').text('Error checking for username avaliablility');
});
答案 1 :(得分:0)
当尝试直接比较AJAX响应时,这是一个常见问题,几乎总是隐藏或特殊字符使得直接比较最困难。而是将您的响应包装在XML或JSON中,不仅看起来更清晰,而且更容易管理。