AJAX表单在提交后不会更新

时间:2016-08-29 01:46:08

标签: ajax django forms django-crispy-forms

我一直在考虑联系表格的ajax请求。表单将使用ajax请求加载字段错误,但它不会在响应后提交表单。需要注意的一点是,我尝试使用表单标记之外的按钮提交表单,但即使标记内有一个按钮,它也只提交一次。

我的ajax脚本:

$('#modal-form').submit(function(e) {
e.preventDefault();
var form = $(this);

$.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    data: form.serialize(),
    success: function(data) {
        if (!(data['success'])) {
            // Here we replace the form, for the
            form.replaceWith(data['form_html']);
            $('#modal-form').off("submit");
        }
        else {
            // Here you can show the user a success message or do whatever you need
            $('#myModal').modal("hide");
        }
    },
    error: function () {
        $('#error-div').html("<strong>Error</strong>");
    }
});
});

我的表格:

{% load crispy_forms_tags %}

<div class="container">
  <!-- Modal -->
  <div class="modal fade container-fluid" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4><span class="glyphicon glyphicon-envelope"></span> Email Me</h4>
          <div id="success-div"></div>
        </div>
        <div class="modal-body">
            <div class="row-fluid">
                <div id="form">
                <form id="modal-form" class="form-horizontal" method="POST" action="{% url 'emailme_success' %}">
                {% csrf_token %}
                {% crispy emailme_form emailme_form.helper %}
                </form>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <div id="error-div" class="pull-left"> </div>
            <button name="submit" type="submit" class="btn btn-success pull-right" id="modal-submit" form="modal-form"><span class="glyphicon glyphicon-send"></span> Send</button>
        </div>
      </div>

    </div>
  </div> 
</div>

0 个答案:

没有答案