javascript - 如何将列表从 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");
}
});
});
解决方案
我在这里使用 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})
推荐阅读
- javascript - 如何创建保留在页面上且不受滚动影响的 HTML 元素?
- mysql - 带有条件 WHERE 子句的 SQL SELECT
- visual-studio - 在 hololens 模拟器中使用 UI 制作的错位 UI
- reactjs - 在电子商务 Mern 堆栈中应用代码拆分?
- sql - 如何编写查询以清理给定问题的表
- postgresql - Postgresql:尝试连接数据库时出现异常
- python - 如何根据另一列的特定值对 python 数据框进行操作?
- c# - 如何在devexpress的gridvew中将按钮添加到最后一行
- for-loop - 批处理 - 如何使用来自 html 的 for /f 设置 var
- c++ - 错误:此处声明了模板。类_LIBCPP_TEMPLATE_VIS basic_stringstream;