gpt4 book ai didi

javascript - 如何使用 AJAX 和 jQuery 发布 Django 表单

转载 作者:IT王子 更新时间:2023-10-29 02:50:51 28 4
gpt4 key购买 nike

我已经查看了大量有关 django AJAX 表单的教程,但每一个都告诉您一种实现方法,它们都不简单,而且我有点困惑,因为我从未使用过 AJAX。

我有一个名为“note”的模型,它的模型形式,在模板中我需要每次 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 发送的数据并更新笔记对象?

最佳答案

既然您使用的是 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>

关于javascript - 如何使用 AJAX 和 jQuery 发布 Django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7335780/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com