我已经检查了大量关于django AJAX表单的教程,但是每一个都告诉你一种方法,其中没有一个是简单的,因为我从未使用过AJAX,所以我有点困惑。
我有一个名为“note”的模型,它是一个模型,在模板内部我需要每次注释元素发送stop()信号(来自jQuery Sortables)django更新对象。
我目前的代码:
views.py
def save_note(request, space_name):
"""
Saves the note content and position within the table.
"""
place = get_object_or_404(Space, url=space_name)
note_form = NoteForm(request.POST or None)
if request.method == "POST" and request.is_ajax:
msg = "The operation has been received correctly."
print request.POST
else:
msg = "GET petitions are not allowed for this view."
return HttpResponse(msg)
JavaScript的:
function saveNote(noteObj) {
/*
saveNote(noteObj) - Saves the notes making an AJAX call to django. This
function is meant to be used with a Sortable 'stop' event.
Arguments: noteObj, note object.
*/
var noteID = noteObj.attr('id');
$.post("../save_note/", {
noteid: noteID,
phase: "Example phase",
parent: $('#' + noteID).parent('td').attr('id'),
title: $('#' + noteID + ' textarea').val(),
message: "Blablbla",
});
}
当前代码从模板中获取数据并将其打印在终端中。我不知道如何处理这些数据。我见过有些人通过jqueryforms管理数据,将数据发送到django。
如何访问AJAX发送的数据并更新注释对象?
答案 0 :(得分:110)
由于您使用的是jQuery,为什么不使用以下内容:
<script language="JavaScript">
$(document).ready(function() {
$('#YOUR_FORM').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#DIV_CONTAINING_FORM').html(response); // update the DIV
}
});
return false;
});
});
</script>
修改强>
正如评论中指出的那样,上述情况有时无效。请尝试以下方法:
<script type="text/javascript">
var frm = $('#FORM-ID');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$("#SOME-DIV").html(data);
},
error: function(data) {
$("#MESSAGE-DIV").html("Something went wrong!");
}
});
return false;
});
</script>
答案 1 :(得分:9)
在您的情况下,您可以使用变量名称访问POST请求中的数据:
request.POST["noteid"]
request.POST["phase"]
request.POST["parent"]
... etc
request.POST对象是不可变的。您应该将值赋给变量,然后对其进行操作。
我建议您使用this JQuery plugin,这样您就可以编写普通的HTML表单,然后将它们“升级”为AJAX。在你的代码中到处都有$ .post是有点乏味的。
此外,使用Firebug上的网络视图(适用于Firefox)或适用于Google Chrome的开发人员工具,以便您查看AJAX调用发送的内容。
答案 2 :(得分:4)
要注意的是将表单作为html剪切到模式返回时。
<强> Views.py 强>
@require_http_methods(["POST"])
def login(request):
form = BasicLogInForm(request.POST)
if form.is_valid():
print "ITS VALID GO SOMEWHERE"
pass
return render(request, 'assess-beta/login-beta.html', {'loginform':form})
返回html剪切的简单视图
表单html Snipped
<form class="login-form" action="/login_ajx" method="Post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="header">Authenticate</h4>
</div>
<div class="modal-body">
{%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_email">Email</label>
<input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
{%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
</div>
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_password">Password</label>
<input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
{%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
</div>
</form>
包含模态的页面
<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog">{% include "assess-beta/login-beta.html" %}</div>
使用include标记加载剪切页面加载,以便在打开模式时可用。
<强> Modal.js 强>
$(document).on('submit', '.login-form', function(){
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
$('#LoginModal').html(data);
}
});
return false;
});
在这种情况下使用.on()就像.live()一样,将提交事件绑定到按钮而不是绑定到文档。
答案 3 :(得分:3)
当其他答案确实有效时,我更喜欢使用jQuery Form Plugin。它完全支持您想要的和更多。后视图在Django部分中照常处理,只返回正在替换的HTML。
答案 4 :(得分:2)
在服务器端,您的django代码可以处理AJAX帖子,就像处理其他表单提交一样。例如,
views.py
def save_note(request, space_name):
"""
Saves the note content and position within the table.
"""
place = get_object_or_404(Space, url=space_name)
note_form = NoteForm(request.POST or None)
if request.method == "POST" and request.is_ajax():
print request.POST
if note_form.is_valid():
note_form.save()
msg="AJAX submission saved"
else:
msg="AJAX post invalid"
else:
msg = "GET petitions are not allowed for this view."
return HttpResponse(msg)
我假设你的NoteForm是一个ModelForm - 应该是 - 所以它有一个save方法。请注意,除了添加save()
命令之外,我还将您的request.is_ajax
更改为request.is_ajax()
,这是您想要的(如果您使用request.is_ajax
,您的代码只会检查是否请求有一个名为is_ajax
的方法,显然它确实如此。
答案 5 :(得分:1)
大多数使用AJAX POST与Django表单的示例,包括官方示例:
https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#ajax-example
ModelForm.clean()
未产生任何错误(form_valid
)时,正常。
但是,它们并没有很难执行:通过AJAX响应将ModelForm
错误转换为Javascript / DOM客户端。
我的可插拔应用程序使用带有客户端视图模型的AJAX响应路由来自动显示基于类的视图AJAX post ModelForm
验证错误,类似于它们在传统HTTP POST中的显示方式:
https://django-jinja-knockout.readthedocs.org/en/latest/forms.html#ajax-forms-processing https://django-jinja-knockout.readthedocs.org/en/latest/viewmodels.html
支持Jinja2和Django模板引擎。