对jquery .ajax .done()函数感到困惑 [英] Confused on jquery .ajax .done() function
问题描述
我对如何使用ajax .done()函数有些困惑.我正在验证表单以检查用户是否存在于数据库中,尽管ajax是最好的方法(仍在学习中).我有一个php文件,如果用户存在,则返回true;如果用户不存在,则返回false.如何将布尔值传递给完成函数的参数?
I'm a bit confused on how to use the ajax .done() function. I'm working on validating a form to check if a user exists in database and though ajax would be the best approach (still learning it). I have a php file that return true if user exists and false if user doesn't exist. How would I pass the boolean into the parameter for the done function?
$(".check").blur(function(){
var username = $(".check").val();
$.ajax({
url: "validateUser.php",
type: "post",
data: "username= " + username
}).done(function(result){
if (result == true){
// User exists
}else{
// User doesn't exist
}
});
});
我希望这是有道理的.我尽力解释了这一点.
I hope that made sense. I did my best to explain it.
推荐答案
我认为应该是result =='true',因为结果是数据字符串
I think it should be result == 'true' as the result is a data string
我刚刚检查了,我是对的,引号使它有效
I just checked, I am correct, the quotes make it work
PHP:
<?php
if($_POST['username']=='sambob'){echo 'true';}else{echo 'false';}
?>
JavaScript
Javascript
username='sambob';
$(".check").blur(function(){
$.post("validateUser.php", { username: username })
.done(function(data) {
if (data == 'true'){
alert("User exists");
}else{
alert("User doesn't exist");
}
});
});
json PHP
<?php
if($_POST['username']=='sambob'){echo'{"exists":true}';}
else{echo'{"exists":false}';}
?>
json Javascript
json Javascript
$(".check").blur(function(){
$.post("validateUser.php", { username : username },
function(user){
if (user.exists == true){
alert("User exists");
}else{
alert("User doesn't exist");
}
}, "json");
});
这篇关于对jquery .ajax .done()函数感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!