我一直在网站上测试一次简单的长期民意测验,由于某种原因,尽管触发它的变量($init
为false
,但我的服务器端代码仍在执行。
我有一个小小的直觉,认为问题出在客户端代码之内,但我似乎无法弄清楚到底是什么。
客户端- JavaScript :
window._Poll: {
listen: function(init){
$.ajax({
url: "/poll.php",
method: "post",
data: { init: init },
success: function(res){
console.log(res);
/* set the init variable to false in the next run */
_Poll.listen(false);
}
});
}, init: function(){
/* set the init variable to true in the first run */
this.listen(true);
}
}
/* on page load */
_Poll.init();
服务器端- PHP :
set_time_limit(0);
session_write_close();
if(isset($_POST["init"]) && ($_POST["init"] == true || $_POST["init"] == false)){
/* the first time this script is called, this variable is true - but for the
* second time and onwards it is false (like it should be) */
$init = $_POST["init"];
echo $init;
/* therefore this block should only be firing once as init is only true once */
if($init){
if(/* some more database checking */){
die("true");
}
} else {
die("false");
}
}
这是第二次及以后的控制台输出
false是
实际上应该是
假假
我一直对此深感困惑,从我发现的情况来看,似乎没有什么可以帮助我。非常感谢您的帮助,
干杯。
答案 0 :(得分:2)
从POST
收到的所有值都是字符串。因此,如果您要传递字符串"false"
,则将其与true
进行松散比较将是一个真实的结果-"false" == true
是真实的,因为字符串是真实的。
检查$_POST["init"] == true || $_POST["init"] == false
没有多大意义,因此您可以检查该值是否等于字符串"true"
或"false"
if(isset($_POST["init"]) && (in_array(strtolower($_POST["init"])), ["true", "false"])){
/* the first time this script is called, this variable is true - but for the
* second time and onwards it is false (like it should be) */
$init = $_POST["init"];
echo $init;
/* therefore this block should only be firing once as init is only true once */
if (strtolower($init) === "true"){
if(/* some more database checking */){
die("true");
}
} else { // Alternatively check if the string is "false", but then you can consider having a default return value other than "false"?
die("false");
}
}
``