如何将datatable的复选框选中数组与表单值合并后通过ajax提交
问题说明
我接触编程仅1个月,遇到如下开发问题:我从datatable中获取到了已勾选的复选框值数组,同时通过表单采集了用户输入数据,想要将表单输入值与复选框选中的每条数据关联合并后,通过ajax发起请求;也可接受不合并数据、将两类数据作为独立参数在ajax中传递的方案,目前不清楚如何实现。
需要调试的代码段
$(document).on("click", '#btn-draft', function() { var user = []; $(".user_checkbox:checked").each(function() { user.push($(this).data('user-id')); }); if(user.length <=0) { alert("Please select records."); } else { var selected_values = user.join(","); var form_values = $("#draft_form").serialize(); var all_values = ??? // idk what to do here? $.ajax({ type: "POST", url: "backend/save.php", cache:false, data:{ type: 6, id : all_values, }, success: function(response) { var ids = response.split(","); for (var i=0; i < ids.length; i++ ) { $( "#myTable" ).load( "index.php #myTable" ); } } }); } });
HTML代码
<body> <main class='main-content'> <!-- partial:index.partial.html --> <div ng-app='ui.bootstrap.demo'> <!-- DROPDOWNS --> <div ng-controller='DropdownCtrl'> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <div class="row"> </div> <div class="row"> <!-- Split button --> <div class="btn-group" dropdown> <button type="button" class="btn btn-danger">Action</button> <button type="button" class="btn btn-danger dropdown-toggle" dropdown-toggle> <span class="caret"></span> <span class="sr-only">Split button!</span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#add-Options" data-toggle='modal'>Add New</a></li> <li class="divider"></li> <li><a href="JavaScript:void(0);" id='draft_multiple'>Create Draft Class</a></li> </ul> </div> <!--datatable HTML --> <table class="table table-striped table-hover" id='myTable'> <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>id</th> <th>Address</th> <th>BD</th> <th>BA</th> <th>City</th> </tr> </thead> <tbody> <?php $result = mysqli_query($conn,"SELECT * FROM properties"); $i=1; while($row = mysqli_fetch_array($result)) { ?> <tr id="<?php echo $row["id"]; ?>"> <td> <span class="custom-checkbox"> <input type="checkbox" class="user_checkbox" data-user-id="<?php echo $row["id"]; ?>"> <label for="checkbox2"></label> </span> </td> <td><?php echo $i; ?></td> <td><?php echo $row["address"]; ?></td> <td><?php echo $row["BD"]; ?></td> <td><?php echo $row["BA"]; ?></td> <td><?php echo $row["city"]; ?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <!-- Modal HTML --> <div id="draftModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form id='draft_form'> <div class="modal-body"> <span> New Draft <br/> Class</span> </div> </div> <div class="content"> <p> <input type="text" placeholder="" id='myInput' name='myInput'> </p> </div> </div> <div class="modal-footer"> <input type="hidden" value="6" name="type"> <button type="button" class="btn btn-default" onclick="" data-dismiss="modal" value="Cancel"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button type="button" class="btn btn-primary" id="btn-draft" data-dismiss="modal"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a> </div> </form> </body>
完整脚本代码
<script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); var checkbox = $('table tbody input[class="user_checkbox"]'); $("#selectAll").click(function(){ if(this.checked){ checkbox.each(function(){ this.checked = true; }); } else{ checkbox.each(function(){ this.checked = false; }); } }); checkbox.click(function(){ if(!this.checked){ $("#selectAll").prop("checked", false); } }); }); $(document).ready(function(){ $('#draft_multiple').on('click', function(){ var id = []; $('.user_checkbox:checked').each(function(i){ id[i] = $(this).val(); }); if(id.length == 0){ alert("Please select records."); }else{ $('#draftModal').modal("show"); $.ajax({ url: 'result.php', method: 'POST', data: {id: id}, success: function(data){ $('#result').html(data); } }); } }); $(document).on("click", '#btn-draft', function() { var user = []; $(".user_checkbox:checked").each(function() { user.push($(this).data('user-id')); }); if(user.length <=0) { alert("Please select records."); } else { var selected_values = user.join(","); var form_values = $("#draft_form").serialize(); var all_values= ??? //idk what to do here? $.ajax({ type: "POST", url: "backend/save.php", cache:false, data:{ type: 6, id : all_values, }, success: function(response) { var ids = response.split(","); for (var i=0; i < ids.length; i++ ) { $( "#myTable" ).load( "index.php #myTable" ); } } }); } }); }); </script>
实现方案
方案1:独立传参(新手优先用,逻辑简单不易出错)
你当前的表单只有1个输入字段,不需要合并数据,直接在ajax的data参数里新增字段分别传两类数据即可,修改代码如下:
// 删掉原来的var all_values= ??? 这一行 $.ajax({ type: "POST", url: "backend/save.php", cache:false, data:{ type: 6, selected_ids: selected_values, // 逗号分隔的选中用户id draft_input: $('#myInput').val() // 表单输入的内容 }, success: function(response) { // 这里不需要循环加载表格,调用一次load就够了 $( "#myTable" ).load( "index.php #myTable" ); } });
后端PHP直接通过$_POST['selected_ids']和$_POST['draft_input']就能拿到对应的数据,处理逻辑也更清晰。
方案2:合并为单参数传递
如果需要把两类数据合并成一个参数传递,直接构造JSON对象即可:
var all_values = { user_ids: user, // 也可以直接传数组,jQuery会自动处理序列化 form_input: $('#myInput').val() }; // ajax的data部分保持原来的id:all_values即可
后端拿到后转成数组处理就可以正常读取两类数据。
额外优化点
- 你当前的HTML中modal部分存在标签嵌套错误,form标签包裹的范围不对,可能会导致表单序列化取不到值,建议调整modal的结构,把form标签完整包裹modal的内容和底部按钮区域。
- success回调里的循环逻辑是冗余的,不管返回多少个id,只需要加载一次表格即可。
内容的提问来源于stack exchange,提问作者Lou H
相关产品推荐
相关产品推荐

