django+ajax实现简单的批量删除
views.py
def deleteall(request): list = request.POST.getlist("val") if request.method =='POST': all = request.POST.getlist('val') for i in all: if i!='': a = Student.objects.get(id=i) a.delete() return redirect(reverse('allstu')) return redirect(reverse('allstu'))
urls.py
path('all/deleteall/', views.deleteall,name = 'deleteall')
html
{% for stu in stus %} <tr> <td><input type="checkbox" onclick="aa()" name="itme" value="{{ stu.id }}"></td> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td>{{ stu.clazz.cname }}</td> <td><a href="{% url 'delete' id=stu.id %}">删除</a></td> <td><a href="{% url 'update' sid=stu.id %}">修改</a></td> </tr> {% endfor %} <tr> <td><a href="{% url 'deleteall' %}" onclick="a()">批量删除</a></td> </tr> <tr> <td><a href="/add/" style="margin: 0 auto">增加</a></td> </tr> </table> <script> onload = function () { alert('欢迎' + "{{ user }}") return false; } </script> <script> function aa() { var one = document.getElementsByName('itme'); one.checkbox = true; } function a() { var vlist =[] var ones = document.getElementsByName('itme') for (var i=0; i<ones.length; i++) { if (ones[i].checked === true) { {#console.log(ones[i].value)#} vlist.push(ones[i].value) } } console.log(vlist); {#alert(vlist)#} if (vlist.length !== 0) { {#console.log(vlist);#} $.ajax({ url: "deleteall/", contenType: 'application/json', type: 'POST', //不加这个,ajax会将结果后边加个[],例如{'vals[]':[4,6,8]} traditional: true, //不加这个,会报服务器终止了一个在运行的程序 async: false, data: ({ 'val': vlist }), success: function () { alert("删除成功"); }, error: function () { alert("删除失败"); }, }) } else { var error_m = "请选择数据"; alert(error_m); } } </script>
个人小站,欢迎访问!http://klvr.xyz