函数“updat-6ren">
gpt4 book ai didi

php - 复选框在 javascript/php 中始终返回 true

转载 作者:行者123 更新时间:2023-11-28 11:25:30 27 4
gpt4 key购买 nike

我正在尝试使用 Ajax/Javascript 响应获取复选框的值,该响应将该值传递给 PHP,以便我可以根据该值执行查询(“已选中”、“未选中”)

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

函数“updateStatus”的Javascript/Ajax代码如下

function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)

functions/ajax.php 中的 PHP 函数

if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}

使用此代码时,它总是返回“已检查”,知道为什么吗?

最佳答案

在 JS 中。 value 将为 truefalse。当您对其中任何一个进行字符串化时,您将得到一个字符串('true''false')。

因此 $_GET['checked'] 将为 "true""false" 两者 ==正确

要在 PHP 端修复此问题,请比较字符串 “true”字符串 “false”;不是 bool 值。

关于php - 复选框在 javascript/php 中始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14282970/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com