How to get an array in Django posted via Ajax

后端 未结 3 1423
北荒
北荒 2020-12-30 18:46

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

JavaScript code:

new_data = [\'a\',\'b\',\'c\',\'d\',\'e\'];
$.get(\'/python         


        
3条回答
  •  误落风尘
    2020-12-30 19:39

    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

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

    views.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,
            })
    

提交回复
热议问题