Skip to content
Advertisement

How to send a list from JavaScript to Django views.py?

How can I send the variable list to Django in the code below?

var list = [];
function add_item(item,next){
  list.push(item.name);
  item.parentNode.style.display = "none";
  next.style.display = "block";
  console.log(list);  }
function remove_item(item,prev){
  for (var i = 0; i <= list.length; i++) {
    if (list[i]===item.name) {
      list.splice(i,1);
    }  }
  item.parentNode.style.display = "none";
  prev.style.display = "block";
  }
$(document).ready(function() {
  $.ajax({
      method: 'POST',
      url: '/food_output',
      data: {'list': list},
      success: function (data) {
           //this gets called when server returns an OK response
           alert("it worked!");
      },
      error: function (data) {
           alert("it didnt work");
      }
  });
});

Advertisement

Answer

I use Django REST Framework here. This solution can submit more complex data to the server. If you use a modern library such as axios, you don’t even need to use JSON.stringify()

$(document).ready(function() {
    list = [1,2,3,4]
    $.ajax({
        method: 'POST',
        url: '/food_output',
        contentType:"application/json",
        data: JSON.stringify({'list': list}),
        success: function (data) {
            //this gets called when server returns an OK response
            alert("it worked!");
        },
        error: function (data) {
            alert("it didnt work");
        }
    });
});
from django.http import JsonResponse
from rest_framework.decorators import api_view

@api_view(['POST'])
def food_output(request):
    print(request.data['list'])
    return JsonResponse({'success':True})

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement