如何使用AJAX从PHP函数中获取真假? [英] How to get true or false from PHP function using AJAX?

查看:70
本文介绍了如何使用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);
    });
}

这篇关于如何使用AJAX从PHP函数中获取真假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆