Ajax:将整数数组发布到 Django

发布于 2024-12-11 17:01:18 字数 945 浏览 0 评论 0原文

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

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 Code:

    /* 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 Code:

@login_required
def delete(request, row_id):                          
     item = get_object_or_404(Items, pk=row_id, user=request.user)
     item.delete()

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜还是长夜 2024-12-18 17:01:18

您可以尝试这样的操作:

$(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 响应。

You could try sometings like this:

$(function(){
    $.post("{% url delete %}", {"ids[]": anSelected}, function(res){
    if(res.ok){
        // remove rows from your table, maybe :)
        // oTable.fnDeleteRow(anSelected);
      }else{
        alert(res.errors); 
      } 
    });
})

On the server:

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

the @ajax_request decorators is from https://bitbucket.org/offline/django-annoying/wiki/Home and let you return json response.

我乃一代侩神 2024-12-18 17:01:18

您需要使用 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
        }
    }
);

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
        }
    }
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文