我正在尝试创建一个包含两个功能部分的页面:
- 用户多次填写并提交的表单
- 每次用户提交表单时都会更新的图表
我正在使用django forms和jQuery我不太明白这个设计是如何组合在一起的。
提交表单后,应该发生以下两种情况之一:图表(并且仅图表)更新,或者如果存在表单验证错误,则表单部分应使用适当的错误消息进行更新。所以实际上一个 Ajax 调用应该更新任一部分。
我只想更新相关的 div
(表单或图表),而不是包含其他 div
、 Logo 和其他静态图形的整个页面。
挑战之一是,如果表单提交顺利,我想返回一个更新图表的 JSON 对象,因为我使用的是第 3 方图表包,但是如果提交失败,返回的内容应该是带有更新后的表单的 HTML 响应。
对于这种行为,django View 的正确模式是什么?
对于这种行为,正确的 javascript\jQuery 模式是什么?
如果这种方法不正确,替代方法是什么?
最佳答案
您需要 JavaScript。例如,使用 jQuery:
$('form').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(data, textStatus, jqXHR){
if (typeof data == 'object') {
// json was returned, update the chart with the json
} else {
// the form had error, the form's html was returned
$('form').html(data);
}
})
})
你可以有这样的Python View :
from django.utils import simplejson
from django import shortcuts
def chart_form(request):
template_full = 'chart_full.html' # extends base.html etc ..
template_form = 'chart_form.html' # just the form, included by chart_full.html
if request.method == 'POST':
form = formClass(request.POST)
if form.is_valid():
// do your chart_data
chart_data = ....
return http.HttpResponse(simplejson.dumps(chart_data), mimetype='application/json')
else:
form = formClass()
if request.is_ajax():
template_name = template_form
else:
template_name = template_full
return shortcuts.render(template_name, {'form': form}, request)
注意:如果您的表单包含文件字段,则该方法将不起作用。在这种情况下,依赖这个插件:http://jquery.malsup.com/form/ (函数ajaxSubmit)
关于jquery - django 表单和 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9431663/