Django jquery AJAX表单提交以查看和显示结果

时间:2018-10-19 03:59:03

标签: javascript jquery ajax django django-forms

关于这部分的内容,有很多不同的文章,我只是不太清楚它们如何组合在一起。

我有name,旁边显示update button。单击update button时,将显示form以更新nameform中有一个save changes button。保存更改后,它将重新加载顶部的name,并且如果再次单击update button,则form应该显示new name信息。

urls.py

path('profile/<int:pk>/', views.customer_profile, name='profile'),
path('update-profile/<int:pk>/', views.update_profile, name='update-profile'),

views.py

def customer_profile(request, pk):
    name = get_object_or_404(CEName, id=pk)
    name_form = NameForm(instance=name)
    return render(
        request,
        'customer/customer_profile.html',
        {'name':name, 'NameForm': name_form}
    )


def update_profile(request, pk):
    if request.POST:
        name_form = NameForm(request.POST)
        if name_form.is_valid():
            name_form.save()
    name = get_object_or_404(CEName, id=pk)
    context = {'name':name, 'NameForm': name_form}
    html = render_to_string('customer/customer_profile.html', context)
    return HttpResponse(html, content_type="application/json")

template.html

<div id="name" class="container d-flex justify-content-between pt-1">
    {{ name }}
    <button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button>
  </div>
  <div id="div_NameForm" class="container" style="display: none;">
    <hr size="3px">
    <form id="NameForm" method="POST" data-url-name="{% url 'customer:update-profile' name.id %}">
      {% csrf_token %}
      {{ NameForm.as_p }}
      <br>
    <button type="submit" id="save_changes" class="btn btn-main button-main btn-block">Save Changes</button>
    </form>
  </div>
<script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script>

jquery.js

$('#save_changes').click(function() {
  var NameForm = $('#NameForm');
  $.ajax({
      type: 'post',
      url: NameForm.attr('data-url-name'),
      data: NameForm.serialize(),
      dataType: 'json',
      success: function(data, textStatus, jqXHR) {
        $('#name').html(data); 
      }
    });
});

update button切换代码不显示。

1 个答案:

答案 0 :(得分:0)

从jQuery开始。
-首先,您可以(可能会说 )在 form 上放置了submit事件处理程序,而不是click事件按钮
-其次,您正在进行AJAX调用,因此应防止在按下按钮时触发的 submit事件中使用.preventDefault()提交表单。这样可以防止页面重新加载。
-第三,在ajax成功回调中,您应该使用text()而不是html(),因为name我猜是文本而不是html,但这只是一个假设。

$('#NameForm').on('submit', function(evt) {
  evt.preventDefault();
  var NameForm = $('#NameForm');
  $.ajax({
      ...
      success: function(response) {
          $(#name).text(response); // or response.name or whatever
      }
  });
})