如果用户登录并更改div颜色,AJAX返回true/false



我试图在用户登录时获得div更改颜色。

php:

if($loggedin === "1"){                      
    return true;
}else{
    return false;
}   

现在它跳过检查,只显示一个绿色的div,无论用户是否登录。

任何帮助都非常感谢!

编辑:

$(document).ready(function() {
            $.ajax({
                type: "POST",
                cache: false,
                setInterval(function() {
                    $.getJSON("includes/widgets/check_status.php", function (res) {
                        if (res === true) { // logged in
                            $('.status').css('background', 'green');
                        } else { //logged out
                            $('.status').css('background', 'red');
                        }
                    });
                }, 3000);
            }); 
        });

你的代码有几个问题:

  • 您没有执行ajax请求:setInterval内部的函数目前什么都不做。你需要调用jQuery的$.ajax(或替代,如$.getJSON)

您可以在setInterval内部修改回调函数:

function() {
    $.getJSON("includes/widgets/check_status.php", function (res) {
        if (res === true) { // logged in
            $('.status').css('background', 'green');
        } else { //logged out
            $('.status').css('background', 'red');
        }
    });
}
  • 当从PHP返回时,你应该回显一些东西。
这种通信的首选数据类型是JSON:
if ($user_data['status'] === "1") {                       
    echo json_encode(true); // In fact json_encode(true) is "true", but being explicit might help in the future
} else {
    echo json_encode(false);
}
exit; // this is required to prevent anything below to be appended to response

我猜你知道==和===在PHP &Javascript。在javascript端使用===不会造成伤害,因为我们从PHP返回布尔数据,我们将其编码为JSON并在javascript端透明地解析JSON($。getJSON为我们做解析)。在PHP方面,如果$user_data['status']不是字符串(例如,如果它是整数1),那么比较将失败。(1 === "1"为假)。这里需要验证类型

您的ajax响应可能有问题。

Try:

console.log(response);

在你的success事件。(您将能够在大多数浏览器的控制台- F12,控制台选项卡中看到输出)。

我不确定你可以这样使用setInterval

Try:

 <script type="text/javascript">
    function check_login(){
    jQuery.ajax({
      type: 'GET',
      url: 'http://www.mysite.com/check.php',
      }, 
      success: function(data, textStatus, jqXHR) {
          console.log(data);
      }
    });
    } 
    $(document).ready(function() {
        setInterval("check_login()", 3000);               
     });
     </script>

当jQuery Ajax返回response text - the first argument of success 时,响应包含headers,而不是纯字符串 true

因此,如果您想检查php条件是否为truefalse,我建议您:

你没有发送Ajax请求:

试试这个:

    $.ajax({
    type: "post",//or GET
    url:"url",
    beforesend: function() {
        //do stuff that you want to run before send
    },
    statusCode: {
        404: function() {
            alert("page not found...");
        }
    },
    success: function(response){                     
                            if(response.indexOf("true") > 0 ) { //logged in
                                $('.status').css('background', 'green');
                            }else { //logged out
                                $('.status').css('background', 'red');
                            }
                        }

这意味着您的响应文本包含php条件作为true