Reputation: 17
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");
}
});
});
Upvotes: 0
Views: 998
Reputation: 103
First join the list
to string; then, on Django view, split it using comma (,
)
$(document).ready(function() {
$.ajax({
method: 'POST',
url: '/food_output',
data: {'list': list.join(",")},
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
});
views.py
def your_method(request):
list = request.POST.get("list")
list = lists.split(",")
Upvotes: 0
Reputation: 1775
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})
Upvotes: 1