如何在手动 POST 中获取所有复选框

一些背景知识,我主要使用 .Net/C# 工作,一生中从未接触过任何 PHP,我的公司给了我一个现有的 PHP 代码,并要求我添加一些功能。


我需要开发的网页是一个餐饮系统。当人数发生变化时,页面会重新计算总价。如果菜单中的每个项目的价格都相似,那么这种方法就很有效。


function RefreshPrice() {

        menuid = getQueryString('menuid');

        $.ajax({

            url: "ajax.php",

            type: "POST",

            data: {

                refreshprice: "refreshprice",

                menuid: menuid,


            },

            success: function(data, textStatus, jqXHR) {


            },

            error: function(jqXHR, textStatus, errorThrown) {

                alert("Error");

            }

        });


    }

但现在有些物品的成本比其他物品高,所以我需要重新计算每个物品的选择。我正在尝试使用隐藏字段来存储该商品的额外价格。


<input type="checkbox" class="validate-checkbox" item-name="<?php echo $item["Name"];?>"

                                  name="menuitem[]" value="<?php echo $item["Id"];?>">

<input type="hidden" class="addprice" name="addprice" value="<?php echo $item["AddPrice"];?>">

但是我如何获取每个选定项目的隐藏字段的值,以便我可以执行类似的操作。


function RefreshPrice() {

        menuid = getQueryString('menuid');

        addprice= document.getElementsByClassName("addprice:checked").val(); //OR $(".addprice:checked").val();

        $.ajax({

            url: "ajax.php",

            type: "POST",

            data: {

                refreshprice: "refreshprice",

                menuid: menuid,

                addprice: addprice,

            },

            success: function(data, textStatus, jqXHR) {


            },

            error: function(jqXHR, textStatus, errorThrown) {

                alert("Error");

            }

        });


    }

抱歉,如果这是一个重复的问题,但我发现的大多数答案是使用表单提交 POST 方法并使用$_POST["addprice"],但这是手动构建 ajax POST。


qq_遁去的一_1
浏览 114回答 3
3回答

呼啦一阵风

经过一些研究和大量测试后,我找到了一种实现你想要的方法,所以这里是一个例子......我一直在我正在构建的应用程序上测试这个示例,因此该示例不会使用您的代码,但方法是相同的,您只需要调整它以与您的代码一起使用...好的,首先让我们创建所需的表并用几行填充它PHP// Establish Connection (change the connection details if necessary)$mysqli = new mysqli ('localhost','root','','test');// Create tablemysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS permissions(&nbsp; &nbsp; id INT(11) AUTO_INCREMENT PRIMARY KEY,&nbsp; &nbsp; name VARCHAR(255) NOT NULL,&nbsp; &nbsp; description VARCHAR(255) NOT NULL)");// Populate tablemysqli_query($mysqli, "INSERT INTO permissions (&nbsp; &nbsp; name,&nbsp; &nbsp; description&nbsp; &nbsp; ) VALUES (&nbsp; &nbsp; &nbsp; &nbsp; 'manage_users',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'Can add/edit users'&nbsp; &nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; &nbsp; &nbsp; ('permission_plus',&nbsp; &nbsp; &nbsp; &nbsp; 'Can manage roles/permissions & access logs'&nbsp; &nbsp; &nbsp; &nbsp; )");&nbsp; &nbsp; ?>因此,在本示例中,我将尝试为我的网络办公室创建一个新角色,并为该角色分配一些现有权限,为此,我们需要创建一个表单,该表单将显示表中的所有现有角色我们刚刚创建了...超文本标记语言<!--Make sure to include JQuery CDN--><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><div id="addRole">&nbsp; &nbsp; <form method="POST" id="addroles">&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="rolename" placeholder="Role Name" />&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="role_description" placeholder="Role Description" />&nbsp; &nbsp; &nbsp; &nbsp; <hr /><span class="title">Include Permissions</span>&nbsp; &nbsp; &nbsp; &nbsp; <div id="checks">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query = mysqli_query($mysqli, "SELECT * FROM permissions");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while($row = $query->fetch_assoc()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $permid = $row['id'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $permname = $row['name'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $permdesc = $row['description'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "<label class='checks' title='$permdesc'>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type='checkbox' class='selected' data-id='$permid'/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$permname</label>";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Add Role" />&nbsp; &nbsp; </form></div>现在,在我们以复选框的形式显示“权限”表中的所有行之后,我们终于可以看到代码中最重要的部分,即使用 JavaScript/JQuery 将选定的复选框存储在数组中并使用 AJAX 将它们传递到服务器...JavaScript$('#addroles').on('submit', function(event){&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; let rolename = $('#rolename').val();&nbsp; &nbsp; let roledesc = $('#role_description').val();&nbsp; &nbsp; let permissions = [];&nbsp; &nbsp; $('.selected').each(function(){&nbsp; &nbsp; &nbsp; &nbsp; if($(this).is(":checked")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; permissions.push($(this).data('id'));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; if(rolename != '' && roledesc != ''){&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: 'addrole.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rolename: rolename,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; roledesc: roledesc,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; permissions: permissions&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }});正如您所看到的,这里的脚本说,提交表单后,首先阻止它使用默认函数,并将表单字段中的值分配给这个特定变量,当涉及到复选框时,创建一个数组,然后每个选中的复选框 - 将存储在 data-id 中的值推送到先前创建的数组中,然后触发 AJAX 并将所有变量传递到服务器,在服务器处理数据后,请告诉我们它所说的内容添加角色.php$mysqli = new mysqli ('localhost','root','','test');$permissions = $_POST['permissions'];foreach($permissions as $permission){&nbsp; &nbsp; echo $permission.' ';}服务器使用foreach函数分解传递的选定复选框数组,并回显存储在每个选定复选框的 data-id 中的值,我们可以在浏览器的控制台中看到它的结果。为了这个例子的外观,这里有一些 CSSCSS#addRole{&nbsp; &nbsp; background-color: rgb(241, 241, 241);&nbsp; &nbsp; position: relative;&nbsp; &nbsp; width:30%;&nbsp; &nbsp; padding:20px;}#addRole input[type='text']{&nbsp; &nbsp; width:80%;&nbsp; &nbsp; height:40px;&nbsp; &nbsp; margin:5px 5px 5px 0px;&nbsp; &nbsp; position: relative;&nbsp; &nbsp; left:50%;&nbsp; &nbsp; transform: translate(-50%);&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; outline:none;}#addRole input[type='submit']{&nbsp; &nbsp; width:80%;&nbsp; &nbsp; height:40px;&nbsp; &nbsp; margin:5px 5px 5px 0px;&nbsp; &nbsp; position: relative;&nbsp; &nbsp; left:50%;&nbsp; &nbsp; transform: translate(-50%);&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; outline:none;}#addRole form hr{&nbsp; &nbsp; width:30%;&nbsp; &nbsp; margin-bottom: 20px;&nbsp; &nbsp; margin-top: 20px;}.checks{&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; padding:20px;&nbsp; &nbsp; text-indent: -20px;&nbsp; &nbsp; background-color: rgb(252, 252, 252);&nbsp; &nbsp; border:1px solid rgb(238, 238, 238);&nbsp; &nbsp; margin: auto;}#checks{&nbsp; &nbsp; position: relative;&nbsp; &nbsp; left:50%;&nbsp; &nbsp; transform: translate(-50%);&nbsp; &nbsp; margin:10px;&nbsp; &nbsp; display: flex-box;&nbsp; &nbsp; text-align: center;}#addRole input[type='checkbox']{&nbsp; &nbsp; width:20px;&nbsp; &nbsp; height:20px;&nbsp; &nbsp; margin:0px 0px 0px 20px;&nbsp; &nbsp; outline:none;&nbsp; &nbsp; text-align: center;}.title{&nbsp; &nbsp; position:relative;&nbsp; &nbsp; left:50%;&nbsp; &nbsp; transform: translate(-50%);&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; font-size: 20px;&nbsp; &nbsp; margin:auto;&nbsp; &nbsp; margin-bottom: 10px;}

慕田峪7331174

我确信您已经意识到根据可以在客户端更改的数据计算价格是一个安全问题。另外,如果服务器端只是添加值,为什么不直接在 javascript 中处理它呢。无论哪种方式,下面的代码都应该收集已检查项目的数据值。<input type="checkbox" class="validate-checkbox priceItems" item-name="<?php echo $item['Name'];?>" name="menuitem[]" value="<?php echo $item['Id'];?>" data-price="<?php echo $item['AddPrice'];?>">您可以将价格作为参数添加到 ajax 函数的数据中或在此处进行求和。var prices = $('.priceItems:checked').map(function() {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $(this).data('price');&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).get();

临摹微笑

我认为将值存储在隐藏表单字段中不是一个好主意。因为出于安全原因,用户可以修改您的旧值。我的建议是,您应该将表单值发送到 PHP 并进行数据库调用并再次比较这些值。如果您发现更改,则更新值,否则保留它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5