在javascript上点击按钮,发布Datatable复选框的多个复选框数据



这是创建数据表的数据表脚本。复选框目标为0,因此每行的第一列始终是一个复选框。该复选框继承了通过django视图发送的{{id}}。

我想以某种方式通过URL将这些ID发送回视图,这样我就可以在数据表中看到我选择的学生ID。

如果有人知道如何用Javascript完成这项工作,那就太好了。当前正在打印ID->console.log(PostData(。帮助更多的人!:(

table_html:

<div  width="100%">
<form action="" method = "post">
{% csrf_token %}
<table id="table_id2" width="100%" class="display">
<thead>
<tr>
<th>Add</th>
<th>title</th>
<th>name</th>
<th>surname</th>
<th>email</th>
<th>location</th>
<th>address</th>
</tr>
</thead>


<tbody>
{% for student in students %}
<tr>
<th>{{ student.ID}}</th>
<th>{{ student.title }}</th>
<th>{{ student.name }}</th>
<th>{{ student.surname }}</th>
<th>{{ student.email }}</th>
<th>{{ student.location }}</th>
<th>{{ student.address }}</th>
</tr>
{% endfor %}
</tbody>
</form>

Javascript:

{% block js %}
<script type="text/javascript" src="https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>
<script>
var PostData;
$(document).ready( function () {
var table = $('#table_id2').DataTable({
"ajax": "{% url 'table_list_addStudents' %}",
"columnDefs": [ {
'targets': 0,
'checkboxes': {
'selectRow': true
}
} ],
select: {
style:    'multi',
},
order: [[ 1, 'asc' ]],


});
var buttons = new $.fn.dataTable.Buttons(table, {
buttons: [
{
text: 'Add Students',
action: function () {

var data = table.rows( { selected: true } ).data().pluck(0).toArray();

if(data.length > 0){
PostData = data
console.log(PostData)
}  
}
},
]
}).container().appendTo('#buttons')

});



</script>
{% endblock %}

Ajax和Django组合需要一个关于成功与否的done.function((。这只是一个运行良好的测试代码。正如你在视图中看到的,数据总是成功的。py

var buttons = new $.fn.dataTable.Buttons(table, {
buttons: [
{
text: 'Add Students',
action: function () {

var data = table.rows( { selected: true } ).data().pluck(0).toArray();

if(data.length > 0){

data = JSON.stringify(data)
$.ajax({
type: 'POST',
url: "",
data: {
'Data' : data,
csrfmiddlewaretoken : '{{ csrf_token }}'
},
dataType: 'json',
}).done(function(data){
if (data.success){
window.location.href = "{% url 'Kurs-page' %}";
}
});
}  
}
},
]
}).container().appendTo('#buttons')

if request.is_ajax():
#doStuff
return JsonResponse({
'success':True
}) #this is going to be returned to ".done " function in js.

它对我有效。如果有人想改进它,那就太酷了。就我而言,我解决了这个问题,只想发布它,这样其他人就可以在django中看到如何处理它。

最新更新