Ajax:将整数数组发布到Django [英] Ajax: post array of integers to Django

查看:94
本文介绍了Ajax:将整数数组发布到Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DataTables .我想让用户选择多个行并将其删除.到目前为止,我可以使用它,因此它使用下面的代码删除选择的第一行.

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 below.

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后端?我想我需要发布anSelected数组,但是不确定如何执行此操作.处理此整数数组需要什么Django代码?

How could I update this to pass all the row ids to the Django back end? I guess I need to POST the anSelected array, but am not sure how to do this. What Django code would I need to process this integer array?

推荐答案

您需要使用simplejson.loads,例如,如果将anSelected数组作为arr传递,则将使用类似的内容

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

并在您的javascript中按照以下方式进行操作:

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

这篇关于Ajax:将整数数组发布到Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆