我正在使用DataTables。我想让用户选择多行并删除它们。到目前为止,我有它的工作,所以它使用下面的代码删除选择中的第一行。
Ajax代码:
/* Add a click handler for the delete row */
$('#delete').click( function() {
/* fnGetSelected returns an array of integers - each int is a db unique id */
var anSelected = fnGetSelected( oTable );
delete_url = '/delete/' + anSelected[0];
$.ajax({
url: delete_url,
type: 'GET',
});
oTable.fnDeleteRow( anSelected[0] );
fnReloadAjax();
} );
Django代码:
@login_required
def delete(request, row_id):
item = get_object_or_404(Items, pk=row_id, user=request.user)
item.delete()
我如何更新这个以将所有行ID传递给Django后端?我想我需要POST一个anSelected数组,但我不知道该怎么做。我需要什么Django代码才能处理这个整数数组?
答案 0 :(得分:6)
你可以试试这样的话:
$(function(){
$.post("{% url delete %}", {"ids[]": anSelected}, function(res){
if(res.ok){
// remove rows from your table, maybe :)
// oTable.fnDeleteRow(anSelected);
}else{
alert(res.errors);
}
});
})
在服务器上:
@ajax_request
def test(request):
ids = request.POST.getlist("ids[]")
try:
Items.objects.filter(id__in=ids).delete()
except:
return {"ok": False, "errors": "your error"}
return {"ok": True}
@ajax_request修饰符来自https://bitbucket.org/offline/django-annoying/wiki/Home,让你返回json响应。
答案 1 :(得分:2)
您需要使用simplejson.loads
,例如,如果您将anSelected数组作为arr
传递,则使用此类内容
from django.utils import simplejson
array = simplejson.loads(request.POST['arr'])
try:
ModelName.objects.filter(pk__in=array).delete()
except:
return HttpResponse(simplejson.dumps({'ok': False}))
return HttpResponse(simplejson.dumps({'ok': True}))
并在你的javascript中有这样的东西:
$.post(
'/delete/',
{arr: anSelected},
function(data){
if(data.ok){
//Everything went smoothly
}else{
//Something failed, you can send extra info from django like the name of the exception thrown if you'd want and display it
}
}
);