首页 > 解决方案 > 将参数传递给 PHP 而不使用表单

问题描述

我有一个看起来像这样的数据库。

+------------+------+
| playername | team |
+------------+------+
| John       | 1    |
| Tim        | 2    |
| ...        | ...  |

在我的页面上,我得到了上面团队 1 的所有名称和下面团队 2 的所有名称。它读出所有玩家的名字,并为每个玩家创建一个带有 onclick 事件的 HTML 元素。当我点击一个元素时,我得到元素的文本......

<?php include_once 'connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"></script>
</head>
<body>
    <?php
        $sql = "SELECT * FROM teams WHERE team = 1;";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                echo "<button href='#' onclick='clickfunction(this)'>".$row['playername']."</button>";
            }
        }
    ?>

    <?php
        $sql = "SELECT * FROM teams WHERE team = 2;";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                echo "<button href='#' onclick='clickfunction(this)'>".$row['playername']."</button>";
            }
        }
    ?>

    <script>
        function clickfunc(obj) {
            var playername = $(obj).text();

            **// SOME CODE TO PASS playername TO change.php**
        }


    </script>

</body>
</html>

我有一个 PHP 文件change.php,它在数据库中查找传递的名称,然后将团队从 1 更改为 2 或其他方式。(sql查询在数据库中工作得很好)

<?php
  include_once 'connection.php';
  $playername = $_GET['playername'];

  $sql = "UPDATE teams SET team = IF(team = 1, 2, 1) WHERE playername = '$playername';";
  mysqli_query($conn, $sql);

  header("Location: index.php");
?>

问题: 现在我有一个问题,我不知道该怎么做,当我单击一个元素并读出文本时,将此文本作为参数发送到chance.php文件,以便 PHP 文件可以使用它。

例如:如果我单击 John,文本“John”将作为参数发送到chance.php并在那里进行处理。结果将是约翰,如果他在上面,现在在下面。或者反过来。

标签: phponclickparameter-passing

解决方案


因为您正在使用 获取值$_GET,所以只需将页面重定向到change.php使用 javascriptwindow.location并将参数放在 URL 中:

function clickfunc(obj) {
     var playername = $(obj).text();
     window.location = "change.php?playername=" + playername
}

推荐阅读