0

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

<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";
}

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

4

3 回答 3

5

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

因此$_GET['checked']将是其中之一"true""false"两者== true

To fix this on the PHP side, compare to the string "true" and the string "false"; not the boolean.

于 2013-01-11T17:02:53.997 回答
4

You are getting $_GET['checked'] as a String. Change to something like:

if($checked == "true") {
    echo "Checked";
} elseif($checked == "false") {
    echo "Not checked";
} else {
    echo "Invalid response";
}
于 2013-01-11T17:04:28.153 回答
0

This might help you in your answer https://stackoverflow.com/a/4228827/90648

You can try replacing the code

"&checked="+value

with

(value ? "&checked=true" : '')

This way you will only send the value true when it is checked, and not send anything (which you can check in PHP with isset)

or you can go with

(value ? "&checked=true" : '&checked=')

which will again, not send anything, thus empty string will be interpreted as false.

于 2013-01-11T17:06:34.693 回答