【问题标题】:Django, submiting a form via AJAXDjango,通过 AJAX 提交表单
【发布时间】:2016-08-20 20:05:37
【问题描述】:

我已经看到类似问题的答案(herehere),但在我的情况下它们都不起作用。我在模板中有一个简单的表单,我正在使用引导程序进行渲染。

提交表单后,响应会直接在浏览器中呈现。当我返回上一页(使用浏览器按钮)时,将执行 AJAX 调用的 success 部分。

forms.py

class QueryForm(forms.Form):
    query = forms.CharField(label='Discover something', max_length=256)

views.py

def query_view(request, id):
    if request.method == 'POST':
        # Just for testing, send True
        response_data = {
            'result': True
        }

        return HttpResponse(json.dumps(response_data), content_type="application/json")
    else:
        try:
            # Create a form and send it to the template
            query_form = QueryForm()

            return render(request, 'query_template.html', {'query_form': query_form})
        except ObjectDoesNotExist:
            return render(request, 'error.html')

urls.py

urlpatterns = [
    url(r'^query', views.query_view, name='query_view'),
    url(r'^', views.home, name='home'),
]

query_template.html

{% extends 'base.html' %}

{% load static %}
{% load bootstrap3 %}

{% block content %}

    {# Display a form #}
    <form method="post" class="form">
        {% csrf_token %}
        {% bootstrap_form query_form %}
        {% buttons %}
            <button class="btn btn-primary" id="query-button">
                {% bootstrap_icon "star" %} Submit
            </button>
        {% endbuttons %}
    </form>
    <ul id="result"></ul>

    <script src="{% static 'scripts/main.js' %}"></script>
{% endblock %}

ma​​in.js

$('#query-button').click(function (event) {
    $.ajax({
        url: "/query/",
        type: "POST",
        data: {},
        cache: false,

        // handle a successful response
        success: function (json) {
            console.log(json); // log the returned json to the console
            $("#result").html("<li>" + json.result + "</li>");
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error: function (xhr, errmsg, err) {
            console.log(xhr.status + ": " + xhr.responseText);
        }
    });
});

// It also includes functions to manage the CRFS token

我一直在玩代码。如果我使用 &lt;input&gt;&lt;button id='query-button'&gt; 的表单,它会在不重新加载页面的情况下呈现响应。

【问题讨论】:

    标签: ajax django django-bootstrap3


    【解决方案1】:

    您需要阻止 HTML 表单的默认提交操作,通过event.preventDefault()

    【讨论】:

    • 不过,我是根据this post写的代码。它不起作用,然后我开始调试并评论了该行。我想我做错了什么。谢谢!
    【解决方案2】:

    您可以使用FormData 代替自定义发送数据,打开以下链接:

    How to send FormData objects with Ajax-requests in jQuery?

    https://developer.mozilla.org/en-US/docs/Web/API/FormData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多