【问题标题】:How to send a list from JavaScript to Django views.py?如何将列表从 JavaScript 发送到 Django views.py?
【发布时间】:2021-06-15 14:49:48
【问题描述】:

如何在下面的代码中将变量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");
      }
  });
});

【问题讨论】:

标签: javascript python django


【解决方案1】:

我在这里使用 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})

【讨论】:

    【解决方案2】:

    首先将list加入字符串;然后,在 Django 视图中,使用逗号 (,) 将其拆分

    $(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(",")
    

    【讨论】:

    • 为什么不像这里描述的那样序列化列表:stackoverflow.com/questions/4505871/…
    • 抛出错误'NoneType'对象没有属性'split'
    • 我也不熟悉 ajax。所以我们必须从提交或不调用这个函数
    • bro ajax 函数没有运行可能是因为当我想 console.log 显示任何内容时
    • 抱歉有错别字,我已经修改了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多