Home >  > 获取前端值,并传给php操作数据库

获取前端值,并传给php操作数据库

一、成果展示

二、前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="mb-4 row">
        <div class="col-lg mt-3">
           <span>Name Set:</span>           
           <select id="gender" class="form-control mt-2" name="nameset">
              <!-- <option value="-2" disabled>-2</option> -->
              <option value="male">Male</option>
              <option value="female">Female</option>
            </select>
           <div id="namesetText" class="mt-2" data-text="Name set(s) for %s">&ThickSpace;<br>&ThickSpace;</div>
        </div>
        <div class="col-lg-auto mt-3">
           <span class="d-block">&ThickSpace;</span>
           <!-- <button class="btn btn-success px-3 mt-2" name = "btn-atc" type="submit">Generate<i class="fas fa-arrow-right ml-3"></i></button> -->
            <button id="myButton" value="按钮值">Generate</button>
        </div>
     </div>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      //直接通过元素的属性Id来直接获取选择下拉菜单的值
     console.log(gender)
    $(document).ready(function() {
        $('#myButton').click(function() {
            var gender = document.getElementById("gender").value; 
            var buttonValue = $(this).val();
            $.ajax({
                url: 'testbutton.php',
                type: 'POST',
                data: { buttonValue: buttonValue,
                        gender:gender    
                },
                success: function(response) {
                    console.log(response);
                }
            });
        });
    });
    </script>
</body>
</html>

三、后端代码

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $buttonValue = isset($_POST['buttonValue']) ? $_POST['buttonValue'] : '';
        $gender =  isset($_POST['gender']) ? $_POST['gender'] : '';
        // 处理按钮值
        echo "接收到的按钮值是: " . $buttonValue;
        echo "gender:". $gender;
    }
?>  

四、参考:

https://www.youtube.com/watch?v=AHmZ1sKNz64&t=393s
https://www.youtube.com/watch?v=AHmZ1sKNz64

暧昧帖

本文暂无标签