如何使用AJAX和jQuery发布django表单

Osc*_*lal 71 javascript django ajax jquery django-templates

我已经查看了大量关于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)
Run Code Online (Sandbox Code Playgroud)

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",
    });
}
Run Code Online (Sandbox Code Playgroud)

当前代码从模板获取数据并将其打印在终端中.我不知道如何处理这些数据.我见过有些人通过jqueryforms管理数据,将数据发送到django.

如何访问AJAX发送的数据并更新注释对象?

Sev*_*ths 115

由于您使用的是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>
Run Code Online (Sandbox Code Playgroud)

编辑

正如评论中指出的那样,上述情况有时无效.请尝试以下方法:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 首先在`views.py`的顶部使用:`来自django.utils import simplejson`.然后执行类似`returnedJSON ['message_type'] ='success'<newline> returnedJSON ['message'] ='成功保存的内容'<newline>返回HttpResponse(simplejson.dumps(returnedJSON),mimetype ="application/json ")`.这样的事情应该有效 (2认同)

小智 10

在您的情况下,您可以使用变量名称访问POST请求中的数据:

request.POST["noteid"]
request.POST["phase"]
request.POST["parent"]
... etc
Run Code Online (Sandbox Code Playgroud)

request.POST对象是不可变的.您应该将值赋给变量,然后对其进行操作.

我建议你使用这个JQuery插件,这样你就可以编写普通的HTML表单,然后将它们"升级"为AJAX.在你的代码中到处都有$ .post是有点乏味的.

此外,使用Firebug上的网络视图(适用于Firefox)或适用于Google Chrome的开发人员工具,以便查看AJAX调用发送的内容.


小智 5

需要注意的是,将表单作为 html 片段返回到模态时。

视图.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})
Run Code Online (Sandbox Code Playgroud)

返回 html 片段的简单视图

表单 html 被剪断

<form class="login-form" action="/login_ajx" method="Post"> 
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</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>
Run Code Online (Sandbox Code Playgroud)

包含模态框的页面

<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog">{% include "assess-beta/login-beta.html" %}</div>
Run Code Online (Sandbox Code Playgroud)

使用 include 标签加载页面加载时的片段,以便在打开模式时可用。

模态.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;
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用 .on() 的工作方式与 .live() 类似,关键是将提交事件绑定到文档,而不是按钮。