Ajax: post array of integers to Django

后端 未结 2 786
[愿得一人]
[愿得一人] 2021-01-06 15:35

I\'m using DataTables. I want to let the user select multiple rows and delete them. So far I have it working so it deletes the first row in the selection using the code belo

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 16:26

    You'd need to use simplejson.loads, for example if you'd pass the anSelected array as arr you'd use something like this

    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}))
    

    and in your javascript this something along these lines:

    $.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
            }
        }
    );
    

提交回复
热议问题