0

在尝试根据复选框内的值开发复选框激活的 mySQL 查询的过程中,我遇到了一个我无法解决的问题,我目前尝试了以下操作

<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

1 回答 1

1

试试这个(代码测试),

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

您将获得第二个参数为真或假;

function updateStatus(id,checked) {
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="+checked, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

你的 PHP 将是:

if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
 //some other query
//Then i can insert the query based on if the checkbox checked or not.
于 2013-01-11T16:13:20.253 回答