【发布时间】:2018-08-23 02:31:15
【问题描述】:
前提:
- 向用户显示一个表格,其中包含带有复选框的对象列表 在他们旁边。
- 用户可以根据需要检查任意数量的复选框。
- 然后用户单击一个按钮将他们重定向到另一个 页面,它只处理那些被选中的对象。
所以我需要通过嵌入在按钮中的 POST 请求将我通过 jQuery 捕获的一组对象 ID 传递给我的下一个视图(从这里在 GraphView 上),以便在下一个重定向页面上仅显示这些对象的列表。如何在我的 URL 和视图中处理它?
我的 jQuery:
// This is the event listener for the button click that would redirect you to the next page
$("#graphRuns").click(function() {
var array = [];
// IDs come from checkboxes. You select which objects you want
// in your next page, then click a button. Here I determine
// which IDs to add to the array through a data-attribute
// on my HTML object templates
choiceContainer.find("input:checked").each(function() {
var run_id = $(this).data("run_id");
array.push(run_id);
});
// I checked and the list of IDs is correct.
console.log(array)
// So I do a post request to the next view I want, passing the array of IDs.
$.post("{% url 'expert_import:chart_runs' %}", {
csrfmiddlewaretoken: "{{csrf_token}}",
array: array
}, function(data) {
// location.reload();
// Redirect here???
}).done();
});
我的网址是我认为我做错的地方:
url(r'^runs/chart$', ChartRunsView.as_view(), name='chart_runs'),
在我的views.py中为GraphView(点击按钮时你去的那个):
def post(self, request, *args, **kwargs):
# I can confirm the array gets to the view here.
print(request.POST)
# This is a strange bit though, the array coming in request.POST
# is named "array[]", when I never added the brackets
# in my JS var declaration, and the next line is only
# grabbing the last element in the incoming array
ids_array = (request.POST.get("array[]"))
runs = []
for run_id in ids_array:
runs.append(Run.objects.filter(pk=run_id))
return render(request, self.template_name, {'runs': runs})
我对此有几个问题。请记住,我是 Django 和一般编程的新手!
我是否应该将 AJAX 帖子定向到显示列表的 URL 我从 (TableView) 中选择的对象,还是应该将帖子定向到 我要在哪个视图中使用 ID 数组 (GraphView)?
我是否应该在 AJAX 帖子的“完成”部分进行重定向? 功能?或者在我从我的 数据库?
我是否应该在我想要重定向的页面的 URL 中有一些 RegEx to,处理对象ID列表? (注意,我不知道有多少 用户将选择的对象)
我觉得我应该将 POST 请求连同某种标志一起发送到 TableView。然后在 TableView 的“def post:”上通过 Python 确定该标志是否存在并处理重定向到我需要的下一页/视图 (GraphView)选定对象的列表。
不确定这里的正确方法是什么。
另外,我可能使用 AJAX 使事情变得过于复杂,但我不确定如何设置 URL 以从 href 中获取列表或如何将其编码到按钮中。
【问题讨论】:
标签: jquery ajax django django-views django-urls