我有一个jQuery Ajax代码,如下所示,其工作在一个删除按钮和一个复选框。
$(".delete-row").click(function(){
$("table
tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
var value = $('chk').val();
$(this).parents("tr").remove();
$.ajax({
url: "/delete/",
// type: "post", // or "get"
data: value
});
});
});
});
这个jquery调用应该删除表格中的选中行,添加的ajax调用将调用django视图。
我的疑问是我在上面的AJAX调用中将复选框值传递给django视图。在这种情况下,django视图如何根据复选框的值来知道要删除哪些表行?
下面是我的表是如何在for循环中创建的
{% for x in dirs %}
<tr id='this_row' style="text-align: center;">
<td>
<input type="checkbox" id="chk" value="this_row" name="record"></td>
<td>
<a href="/contents?query_name={{ x|urlenchode }}" id="this_row1" style="text-decoration: none;">{{ x.name }}</a>
</td>
<td>
{{ x.created_date }}
</td>
<td>
{{ x.description }}
</td>
</tr>
{% endfor %}
下面是删除按钮
<button type="submit" name="erase" class="delete-row">Delete Row</button>
发布于 2018-06-11 14:43:19
只需id
将该行的value
属性添加到复选框,以便你的ajax将发送一个ID列表。而不是this_row
添加{{x.id}}
实例ID
{% for x in dirs %}
<tr id='tr-{{x.id}}' style="text-align: center;">
<td><input type="checkbox" id="chk-{{x.id}}" value="{{x.id}}" name="record"></td>
<td>
<a href="/contents?query_name={{ x|urlenchode }}" id="link-{{x.id}}" style="text-decoration: none;">{{ x.name }}</a></td>
<td>{{ x.created_date }}</td>
<td>{{ x.description }}</td>
</tr>
{% endfor %}
在你的ajax中,你可以使用它
// send this array via ajax
$(".delete-row").click(function(){
var id_list = new Array();
$("input[name=record]:checked").each(function(){
id_lists.push($(this).val());
$(this).parent("tr").remove(); // Remove the row,
// the correct is parent() without 's', not parents()
});
// with type:'post', don't forget the csrf_token
$.ajax({
url: "/delete/",
type: "post",
data: {
id_list:id_list,
csrfmiddlewaretoken:"{{ csrf_token }}"
},
});
});
你可以检索id_list
包含所有选定的行reqest.POST.getlist('id_list[]')
。万一它是一个GET请求reqest.GET.getlist('id_list[]')
https://stackoverflow.com/questions/-100005296
复制相似问题