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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7335780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:51:31  来源:igfitidea点击:

How to POST a django form with AJAX & jQuery

javascriptjqueryajaxdjangodjango-templates

提问by Oscar Carballal

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.

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

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.

我有一个名为“note”的模型,它的模型形式,在模板中我需要每次 note 元素发送 stop() 信号(来自 jQuery Sortables)django 更新对象。

My current code:

我目前的代码:

views.py

视图.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:

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",
    });
}

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.

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

How can I access the data sent by AJAX and update the note object?

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

回答by Sevenearths

Since you are using jQuery why not use the following:

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

EDIT

编辑

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>

回答by Gerardo Curiel

You can access the data on the POST request using the name of the variable, in your case:

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

request.POST["noteid"]
request.POST["phase"]
request.POST["parent"]
... etc

The request.POST object is inmutable. You should assign the value to a variable, and then manipulate it.

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

I would advise you to use this JQuery plugin, so you can write normal HTML forms and then get them "upgraded" to AJAX. Having $.post everywhere in you code is kind of tedious.

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

Also, use the Network view on Firebug(for Firefox) or the Developer Tools for Google Chrome so you can view what's being sent by you AJAX calls.

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

回答by JUhrig

Something to look out for is when returning the form as an html snipped to a modal.

需要注意的是将表单作为 html 剪切到模态时返回。

Views.py

视图.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})

Simple view to return the html snipped

返回截取的 html 的简单视图

Form html Snipped

表单 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>

Page containing the modal

包含模态的页面

<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog">{% include "assess-beta/login-beta.html" %}</div>

Use the include tag to load the snipped on page load so it is available when you open the modal.

使用 include 标签加载页面加载时的截图,以便在打开模态时可用。

Modal.js

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;
});

Using the .on() in this case work like .live() the key being binding the submit event not to the button but to the document.

在这种情况下使用 .on() 像 .live() 一样工作,键将提交事件绑定到文档而不是按钮。

回答by Armando Pérez Marqués

As the other answers do work, I prefer to use the jQuery Form Plugin. It fully supports what you want and more. The post view is handled as usual in the Django part, just returning the HTML that is being replaced.

由于其他答案确实有效,我更喜欢使用jQuery Form Plugin。它完全支持您想要的以及更多。post 视图在 Django 部分像往常一样处理,只返回被替换的 HTML。

回答by user931920

On the server side, your django code can process the AJAX post the same way it processes other form submissions. For example,

在服务器端,您的 django 代码可以像处理其他表单提交一样处理 AJAX 帖子。例如,

views.py

视图.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)

I've assumed your NoteForm is a ModelForm -- which it should be -- so it has a save method. Note that in addition to adding the save()command, I changed your request.is_ajaxto request.is_ajax(), which is what you want (if you use request.is_ajaxyour code will just check whether the request has a method called is_ajax, which obviously it does).

我假设您的 NoteForm 是一个 ModelForm —— 它应该是 —— 所以它有一个 save 方法。请注意,除了添加save()命令之外,我将您更改request.is_ajaxrequest.is_ajax(),这就是您想要的(如果您使用request.is_ajax您的代码,将只检查请求是否有一个名为 的方法is_ajax,显然它确实如此)。

回答by Dmitriy Sintsov

Most of examples of using AJAX POST with Django forms, including the official example:

大多数在 Django 表单中使用 AJAX POST 的示例,包括官方示例:

https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#ajax-example

https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#ajax-example

are fine when ModelForm.clean()did not produce any errors (form_valid). However, they do not perform hard part: translating ModelFormerrors via AJAX response to Javascript / DOM client-side.

ModelForm.clean()没有产生任何错误时很好( form_valid)。但是,它们不执行困难的部分:ModelForm通过 AJAX 响应将错误转换为 Javascript / DOM 客户端。

My pluggable application uses AJAX response routing with client-side viewmodels to automatically display class-based view AJAX post ModelFormvalidation errors similar to how they would be displayed in traditional HTTP POST:

我的可插入应用程序使用带有客户端视图模型的 AJAX 响应路由来自动显示基于类的视图 AJAX 后ModelForm验证错误,类似于它们在传统 HTTP POST 中的显示方式:

https://django-jinja-knockout.readthedocs.org/en/latest/forms.html#ajax-forms-processinghttps://django-jinja-knockout.readthedocs.org/en/latest/viewmodels.html

https://django-jinja-knockout.readthedocs.org/en/latest/forms.html#ajax-forms-processing https://django-jinja-knockout.readthedocs.org/en/latest/viewmodels.html

Both Jinja2 and Django Template Engine are supported.

支持 Jinja2 和 Django 模板引擎。