如何使用AJAX从PHP函数中获取真假?

问题描述:

我使用var_dump($ result)测试了 status.php 返回值,并在如下的check()函数中对其进行了警告:

I tested status.php return value with var_dump($result) and alerted it out in check() function like this:

function check() {
    $.ajax({
        url: "status.php"
    }).done(function(data) {
        alert(data);
    });
}

并且根据情况确实返回了true或false,但是当我在check()函数中检查数据是true还是false时,它总是返回false.

and it did return true or false depending on situation, but when I check if data is true or false inside of check() function it always returns false.

status.php:

<?php 
function status(){
    if(logged() === true) {
        $result = true;
    } else {
        $result = false;
    }
    return $result;
}
status();
?>

check()函数:即使有时应为"true",也始终会发出"false"警报

check() function: always alerts "false" even though sometimes should be "true"

function check() {
    $.ajax({
        url: "status.php"
    }).done(function(data) {
        if(data === true){
            alert("true");
        } else {
            alert("false");
        }
    });
}

您没有将status()函数的返回值发送回PHP.使用:

You're not sending the return value of the status() function back to PHP. Use:

echo json_encode(status());

并更改AJAX调用以期望JSON响应.

And change the AJAX call to expect a JSON response.

function check() {
    $.ajax({
        url: "status.php",
        dataType: 'json'
    }).done(function(data) {
        alert(data);
    });
}