如何使用 Django、Ajax、jQuery 在不刷新页面的情况下提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11647715/
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-26 10:48:11  来源:igfitidea点击:

How to submit form without refreshing page using Django, Ajax, jQuery?

jqueryajaxdjango

提问by webfanks

I am newbie working with django. I need simple example. How to submit form (post) without refreshing page using Django, Ajax, jQuery?

我是与 Django 一起工作的新手。我需要简单的例子。如何使用 Django、Ajax、jQuery 在不刷新页面的情况下提交表单(发布)?

This is my form, views and template:

这是我的表单、视图和模板:

views.py

视图.py

from django.shortcuts import *
from django.template import RequestContext
from linki.forms import *

def advert(request):
    if request.method == "POST":
        form = AdvertForm(request.POST)

        if(form.is_valid()):
            print(request.POST['title'])
            message = request.POST['title']

        else:
            message = 'something wrong!'


        return render_to_response('contact/advert.html',
                {'message':message},
            context_instance=RequestContext(request))

    else:
        return render_to_response('contact/advert.html',
                {'form':AdvertForm()},
            context_instance=RequestContext(request))

forms.py (form using "ModelForm")

forms.py(使用“ModelForm”的表单)

from django import forms
from django.forms import ModelForm
from linki.models import Advert


class AdvertForm(ModelForm):
    class Meta:
        model = Advert

TEMPLATES (form html code)

模板(表单 html 代码)

<html>
<head>

</head>
    <body>
    <h1>Leave a Suggestion Here</h1>
        {% if message %}
            {{ message }}
        {% endif %}
        <div>
            <form action="" method="post">{% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit Feedback" />
            </form>
        </div>
    </body>
</html>

回答by pahko

if you are planning to use an ajax submit with jquery you should not return html from your view.. I propose you to do this instead:

如果你打算使用 jquery 的 ajax 提交,你不应该从你的视图中返回 html.. 我建议你这样做:

html:

html:

<html>
<head>
</head>
<body>
    <h1>Leave a Suggestion Here</h1>
        <div class="message"></div>
        <div>
            <form action="" method="post">{% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit Feedback" />
            </form>
        </div>
</body>
</html>

the js

js

$('#form').submit(function(e){
    $.post('/url/', $(this).serialize(), function(data){ ... 
       $('.message').html(data.message);
       // of course you can do something more fancy with your respone
    });
    e.preventDefault();
});

the views.py

视图.py

import json
from django.shortcuts import *
from django.template import RequestContext
from linki.forms import *

def advert(request):
    if request.method == "POST":
        form = AdvertForm(request.POST)

        message = 'something wrong!'
        if(form.is_valid()):
            print(request.POST['title'])
            message = request.POST['title']

        return HttpResponse(json.dumps({'message': message}))

    return render_to_response('contact/advert.html',
            {'form':AdvertForm()}, RequestContext(request))

so that way you put the response in the messagediv. instead of returning plain html you should return json.

这样你就可以将响应放在messagediv 中。您应该返回 json 而不是返回纯 html。

回答by Jubin Thomas

<script type="text/javascript">
$(document).ready(function() {
    $('#form_id').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..
                $('#success_div).html(response); // update the DIV
            },
            error: function(e, x, r) { // on error..
                $('#error_div).html(e); // update the DIV
            }
        });
        return false;
    });
});
</script>

回答by Alexander Larikov

$('#form-id').submit(function(e){
    $.post('your/url', $(this).serialize(), function(e){ ... });
    e.preventDefault();
});

回答by Alex Jolig

Hereis a perfect tutorial for it. I'll include the important parts:

是一个完美的教程。我将包括重要部分:

first add this jQuery scriptsto main.jsand link it to your page.

首先添加该jQuery的脚本main.js并将其链接到您的网页。

Add this codes to the main.js(I'll include my version for sending blog comment)

将此代码添加到main.js(我将包含用于发送博客评论的版本)

// Submit post on submit
$('#comment-form').on('submit', function(event){
    event.preventDefault();
    create_post();
});

// AJAX for posting
function create_post() {
    $.ajax({
        url : "/blogcomment/", // the endpoint
        type : "POST", // http method
        data : {
            blog_id: blog_id,
            c_name : $('#comment-name').val(),
            c_email:  $('#comment-email').val(),
            c_text:  $('#comment-text').val(),
        }, // data sent with the post request

        // handle a successful response
        success : function(json) {
            $('#comment-name').val(''); // remove the value from the input
            $('#comment-email').val(''); // remove the value from the input
            $('#comment-text').val(''); // remove the value from the input
            $('#comment-form').prepend("<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>&times;</button>" + json.result +"</div>");
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#comment-form').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>&times;</button>Oop! Error happend!</div>"); // add the error to the dom
            //console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
}

my views.pyfor getting comment looks like this:

views.py的评论看起来像这样:

def get_blog_comment(request):
    if request.method == 'POST':
        blog_id = request.POST.get('blog_id') 
        user = request.POST.get('c_name')
        email = request.POST.get('c_email')
        comment = request.POST.get('c_text')
        date = jdatetime.datetime.now().strftime("%Y-%m-%d");
        response_data = {}
        blogcomment = Comments(blog_id = blog_id, date = date, name = user, email = email, comment_text = comment)
        blogcomment.save()

        response_data['result'] = 'Success!!.'

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

And finally the url part for urls.pywhich is not included in the original tutorial:

最后urls.py是原始教程中未包含的 url 部分:

path('blogcomment/', views.get_blog_comment, name='get_blog_comment'),