我对如何使用ajax .done()函数感到有点困惑。我正在验证一个表单以检查用户是否存在于数据库中,尽管ajax是最好的方法(仍在学习它)。我有一个php文件,如果用户存在则返回true,如果用户不存在则返回false。如何将布尔值传递给done函数的参数?
$(".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
}
});
});
我希望这是有道理的。我尽力解释它。
我认为应该是结果=='true',因为结果是数据字符串
我刚刚检查过,我是正确的,引号使其成功
PHP:
<?php
if($_POST['username']=='sambob'){echo 'true';}else{echo 'false';}
?>
使用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
$(".check").blur(function(){
$.post("validateUser.php", { username : username },
function(user){
if (user.exists == true){
alert("User exists");
}else{
alert("User doesn't exist");
}
}, "json");
});
在你的PHP方面,你应该回应一些 json string
,例如,我会这样做 validateUser.php
:
//Check your database etc.
$user_exists = array('error'=>false,'user'=>true);
echo json_encode($user_exists);
而不是与jQuery:
$.ajax({
url: "validateUser.php",
type: "post",
data: "username= " + username,
dataType: "json",
}).done(function(result){
if (result.error == false){
//No errors, check user
if(result.user == true)
alert("Exists"); //now do some stuff
else
alert("User don't exists");
}else{
// There is an error
}
});
成功:它将返回XHR成功状态,例如:200
完成:一旦XHR获得成功,它将完成并返回返回数据
试试下面的代码
$.ajax({
type: "POST",
url: Url,
data: dataParameter,
async: true,
success: function(results, textStatus) {
debugger;
console.log("success : " + results);
},
error: function(xhr, status, error)
{
console.log("error : " + xhr.responseText);
}
}).done(function(results) {
debugger;
console.log("done : " + results);
});