首页 > 解决方案 > 如何将列表从 JavaScript 发送到 Django views.py?

问题描述

如何list在下面的代码中将变量发送到 Django?

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");
      }
  });
});

标签: javascriptpythondjango

解决方案


我在这里使用 Django REST 框架。该解决方案可以向服务器提交更复杂的数据。如果您使用诸如 的现代库axios,您甚至不需要使用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})

在此处输入图像描述


推荐阅读