我使用all things you told me进行了更新,这是我的结果。 完整更新:
$(document).ready(function(){
$("#submit").submit(function(e){
e.preventDefault();
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
request.done(function() {
console.log(result);
if(request.result == 1) {
alert("yes")
} else {
alert("no")
}
});
});
});
check.php:
$usernameChecker = new UsernameChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
if(!empty($data)) {
if ($usernameChecker->check_regex($data)) {
if($usernameChecker->check_length($data)) {
if (!$usernameChecker->check($data)) {
echo json_encode(array("error" => "Username already taken" , "result" => 0));
} else {
echo json_encode(array("error" => "Username available" , "result" => 1));
}
} else {
echo json_encode(array("error" => "Username too long" , "result" => 0));
}
} else {
echo json_encode(array("error" => "Allowed symbols: a-z , A-Z , 1-9 and \"_\"" , "result" => 0));
}
} else {
echo json_encode(array("error" => "You forgot to type your username" , "result" => 0));
}
这就是我现在所拥有的,只是控制台说:
“结果未定义”
SO:
当我提交空输入时,我的请求未定义。
当我提交填写的输入时,我会收到警告“否”。此外这一部分:
“用户名可用”
标记为红色。
但是控制台中的data.result是“1”吗?
答案 0 :(得分:3)
将数据分配给另一个在$ .ajax函数之外使用的变量
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
以下是您的编辑
request.done(function() {
console.log(result.result);
if(result.result == 1) {
alert("yes")
} else {
alert("no")
}
});