Javascript POST数据转到GET PHP数组

时间:2016-04-19 08:21:40

标签: javascript php ajax

我花了几个小时搞清楚为什么我的Ajax脚本不起作用。然后我发现用POST发送的请求变量进入$ _GET。这是为什么?这是我最后的工作代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Groups</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<?php
include "navigation.php";
$conn=new mysqli('',databaseuser,databasepassword,database);
$q="SELECT * FROM User_groups";
$r=$conn->query($q);
if($r)
{
    echo "<table><tr><th>Name</th><th>Delete topics</th><th>Edit others' content</th><th>Delete comments</th>
        <th>Deactivate users</th><th>Delete own topics</th></tr>";
    $number=0;
    while($row=$r->fetch_array())
    {
        $n=$row['groupName'];
        $dt=$row['canDeleteTopics'];
        $dc=$row['canDeleteComments'];
        $du=$row['canDeactivateUsers'];
        $dot=$row['canDeleteOwnTopics'];
        $eo=$row['canEditOthersContent'];

        echo "<tr><td id='name$number'>$n</td>
        <td><button id='canDeleteTopics$number' onclick='toggle(this)'>$dt</button></td>
        <td><button id='canEditOthersContent$number' onclick='toggle(this)'>$eo</button></td>
        <td><button id='canDeleteComments$number' onclick='toggle(this)'>$dc</button></td>
        <td><button id='canDeactivateUsers$number' onclick='toggle(this)'>$du</button></td>
        <td><button id='canDeleteOwnTopics$number' onclick='toggle(this)'>$dot</button></td>
        </tr>";
        $number++;
    }
    echo "</table>";

}
?>
<script>
    function toggle(button) {
        var id=button.id
        var position=id.search(/[0-9]/)
        var columnname=id.slice(0,position)
        var number=id.slice(position);
        //console.log(number)
        var id2='name'+number;
        var group=document.getElementById(id2).innerHTML
         var request=new XMLHttpRequest();
        request.onreadystatechange=function ()
        {
            if(request.readyState==4)
            {
                location.reload()
                console.log(request.responseText)
            }
        }
        request.open('POST','editclass.php?columnname='+columnname+'&class='+group,true)
        request.send(null)
    }
</script>
</body>
</html>

editclass.php:

<?php
$columnname=$_GET['columnname'];
$name=$_GET['class'];
include "constants.php";
$conn=new mysqli('',databaseuser,databasepassword,database);
if($conn)
{
    $q="UPDATE User_groups SET $columnname = NOT $columnname WHERE groupName='$name'";
    $res=$conn->query($q);
    if($res) echo "Toggled ".$columnname;
    else echo $conn->error;
}
else echo $conn->error;

如果我使用$ _POST,它似乎是空的。

1 个答案:

答案 0 :(得分:0)

您需要在send()调用中发送POST参数,如下所示:

var group=document.getElementById(id2).innerHTML
var params = "id="+button.id+"&position="+id.search(/[0-9]/)+"&columnname="+id.slice(0,position)+"&number=id.slice(position)+"&id2="+group+"&name="+number;
request.send(params);