我用 var_dump($result) 测试了状态.php返回值,并在 check() 函数中提醒它,如下所示:
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
alert(data);
});
}
它确实根据情况返回真或假,但是当我在 check() 函数中检查数据是真还是假时,它总是返回假。
状态.php:
<?php
function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
return $result;
}
status();
?>
check() 函数:总是提醒"false",即使有时应该是"true"
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data === true){
alert("true");
} else {
alert("false");
}
});
}
你不会将status()
函数的返回值发送回 PHP。用:
echo json_encode(status());
并将 AJAX 调用更改为预期 JSON 响应。
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
你只是像这样回声$result
Ajax 不返回值,因此我们必须回显它。
<?php function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
echo $result; } status(); ?>
然后应该是这样的
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == "true"){
alert("true");
} else {
alert("false");
}
}); }
使用
**dataType: 'json'**
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
和状态.php使用
echo json_encode(status());
在 ajax 中,您无法通过返回方法获取响应。 获取值"echo",无论函数中的结果如何,例如
function status(){
if(logged() === true) {
$result = "1";
} else {
$result = "0";
}
echo $result;exit;
}
您将在 Ajax 成功函数中获得值 1 或 0
Ajax 可能不返回布尔true
或false
,而是返回一个字符串。
因此,请尝试将true
放在双引号中:
if(data=="true")
您还可以对数据使用 trim
函数来确保返回的数据中不存在空格,如下所示:
if($.trim(data)=="true")
只需删除类型检查,即"==="替换为"=="
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == true){
alert("true");
} else {
alert("false");
}
});
}