2016-04-26 66 views
0

我看到類似問題的答案(herehere),但它們都不適用於我的情況。我在模板中有一個簡單的表單,我使用引導進行渲染。Django,通過AJAX提交表格

一旦我提交表單,響應直接在瀏覽器中呈現。當我回到上一頁(使用瀏覽器的按鈕)時,成功部分AJAX調用被執行。

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 %} 

main.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 

我一直在玩的代碼。如果我使用的表單是<input><button id='query-button'>,它將呈現響應而不重新加載頁面。

回答

2

您需要防止默認提交HTML表單的作用,通過event.preventDefault()

+0

但是,我寫了基於[此帖](https://realpython.com/blog/python/django-and-ajax-form-submissions/)的代碼。它沒有工作,然後我開始調試並評論該行。我想我還在做其他事情。謝謝! – Manuel