如何使用AJAX和功放发表Django的形式; jQuery的 [英] How to POST a django form with AJAX & jQuery
问题描述
我已经签出吨教程Django的AJAX的形式,但他们每个人告诉你做这件事的一种方式,他们都不是简单的,我有点困惑,因为我从来没有使用AJAX。
I've checked out tons of tutorials for django AJAX forms, but each one of them tells you one way of doing it, none of them is simple and I'm a bit confused since I've never worked with AJAX.
我有一个名为注的模式,一个的ModelForm它,并在模板中我需要每次记要素发送停止()信号(从jQuery的Sortables)Django的更新对象。
I have a model called "note", a modelform for it, and inside the template I need that everytime a note element sends the stop() signal (from jQuery Sortables) django updates the object.
我目前的code:
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",
});
}
目前的code从模板中获取数据并打印在终端。我不知道我可以操纵这些数据。我见过一些人设法通过jqueryforms的数据,将数据发送到Django的。
The current code gets the data from the template and prints it in the terminal. I don't know how I can manipulate this data. I've seen some people manages the data through jqueryforms to send the data to django.
我如何可以访问由AJAX发送的数据,并更新笔记对象?
How can I access the data sent by AJAX and update the note object?
推荐答案
由于您使用jQuery为什么不使用下列内容:
Since you are using jQuery why not use the following:
<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>
修改
正如在评论中有时上面将无法正常工作。因此,请尝试以下操作:
As pointed out in the comments sometimes the above won't work. So try the following:
<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>
这篇关于如何使用AJAX和功放发表Django的形式; jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!