jQuery 如何在通过 Ajax 发布的 Django 中获取数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12101658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:19:05  来源:igfitidea点击:

How to get an array in Django posted via Ajax

ajaxdjangojquerypython-2.7

提问by Erez

When I try to send an array to Django via Ajax (jQuery)

当我尝试通过 Ajax (jQuery) 向 Django 发送数组时

JavaScript code:

JavaScript 代码:

new_data = ['a','b','c','d','e'];
$.get('/pythonPage/', {'data': new_data},function(data){});

and I try to read the array:

我尝试读取数组:

Python:

Python:

request.GET.get("data[]")

I get only the last array value:

我只得到最后一个数组值:

'e'

What am I doing wrong?

我究竟做错了什么?

回答by Yuji 'Tomita' Tomita

You're looking for the QueryDict's getlist

你正在寻找QueryDictgetlist

request.GET.getlist('data')
request.GET.getlist('data[]')
request.GET.getlist('etc')

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict.getlist

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict.getlist

回答by Michael Stachura

Quite old question but let me show you full working code for this. (Good for newbie :)

很老的问题,但让我向您展示完整的工作代码。(适合新手:)

In your template

在您的模板中

data = {
    'pk' : [1,3,5,10]
}

$.post("{% url 'yourUrlName' %}", data, 
    function(response){
        if (response.status == 'ok') {
            // It's all good
            console.log(response)
        } else {
            // Do something with errors
        }
    })

urls.py

网址.py

urlpatterns = [
    url(r'^yourUrlName/', views.yourUrlName, name='yourUrlName'), #Ajax
]

views.py

视图.py

from django.views.decorators.http import require_POST
from django.http import JsonResponse


@require_POST
def yourUrlName(request):
    array = request.POST.getlist('pk[]')

    return JsonResponse({
            'status':'ok',
            'array': array,
        })

回答by Michael Stachura

Just use request.GET.getlist('data[]')

只需使用 request.GET.getlist('data[]')