$("input[type='checkbox']").on("change",function(){
if($(this).is(":checked")){
$.ajax({
url: portfolio_data_url,
type: 'POST',
data: "id="+$(this).val(),
success:function(r){
// succcess call
}
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<div><input type="checkbox" value="0" checked>All</div>
<div><input type="checkbox" value="1">AppID</div>
<div><input type="checkbox" value="2">Vendor</div>
</form>
我有几个复选框,其值是使用 POST 请求传递的。如果选中一个复选框,则该值将传递给 POST 请求。
但我已经有了传递 POST 请求的代码:
list.js
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST"
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
如何将代码集成到 list.js
中,以便一次查询即可完成所有操作。
因为现在发送了两个不同的请求,导致信息输出不正确。
最佳答案
您可以使用 .DataTable
函数在一个请求中发送复选框选中的值,如下所示:
试试这个:
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST",
"data": function(d){
var ids = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
d.ids = ids;
}
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
在 Datatable
中使用 data
参数作为函数允许将附加数据发送到服务器
注意:您将获得作为数组的选中复选框值,您可以在 .get()
之后使用 .join(',')
> 将值作为逗号分隔的字符串发送以直接在查询中使用
此外,当用户选中任何复选框时,我们可以刷新数据表 ajax 以发送更新的选中复选框,如下所示:
$("input[type='checkbox']").on("change",function(){
table.ajax.reload();
});
关于javascript - 将两个请求集成到一个 Javascript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000476/