返回ajax响应

时间:2014-03-10 08:27:28

标签: php jquery ajax

我有一个功能

function chkLogin() {
    $.get("setAlert.php", function (data) {
        $(".result").html(data);
        if (data == 'Not logged in') {
            alert("not logged in.");
        } else {
            alert("success");
        }
    });
}

setAlert.php

if (!isset($login_session)) { 
    return "Not logged in";
   }
   else{
 return "logged in";
}

它会提醒成功,因为数据是空白的。 那么如何将数据设置为“登录”或“未登录”? 请帮忙。

3 个答案:

答案 0 :(得分:1)

您无需返回任何内容

只需使用echo

if (!isset($login_session)) {
    echo "Not logged in";
} else {
    echo "logged in";
}

阅读jQuery Ajax call tutorial


如果用户未登录,请使用Window.location

重定向用户
$.get("setAlert.php", function (data) {
    $(".result").html(data);
    if (data == 'Not logged in') {
        window.location = "index.php"; // redirect page if user not logged in
    } else {
        alert("success");
    }
});

答案 1 :(得分:0)

如果您想查看登录信息。 通常使用cookie来检查。 你可以调用php cookie方法来保存cookie,并检查客户端的cookie数据。

sample

答案 2 :(得分:0)

尝试使用json数据处理响应。

用json

调用ajax
function chkLogin() {
$.get("setAlert.php", function (data) {
    $(".result").html(data);
    if (data.status == true) {
        alert("success");
    } else {
        alert("not logged in.");
    }
},"json");
}

修改setAlert.php

$result = array();
if (!isset($login_session)) { 
$result['status'] = false;}
else{ $result['status'] = true;
}
echo json_encode($result);