1. 程式人生 > 實用技巧 >Django中的Ajax表單提交(小Demo)

Django中的Ajax表單提交(小Demo)

Ajax是以一種與伺服器交換資料的技術,可以在不過載整個頁面的情況下更新網頁的一部分。它也可以運用在Django專案的表單中,與普通的views函式不一樣的是:表單所在的網頁上必須有JavaScript指令碼,該指令碼一方面對提交資料給view方法,另一方面根據view返回的response對現有的頁面進行調整。

下面是一個簡單的例子,通過這個例子,總結其步驟和需要注意的地方。

  • 首先是html
# base.html
<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title Page</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.3/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<!-- Bootstrap JavaScript -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
{% block body_block %}
{% endblock %}
 </body>
</html>
# testAjax.html
{% extends 'base.html' %}
{% block body_block %}
<h4>FeedBack</h4>
<div class="row">
    <div id="feedbackmessage">
        Hell
    </div>
</div>
<form  method="POST" id="feedbackform" action='{% url "testapp:feedback" %}'>
    {% csrf_token %}
    <div class="row">
        <div class="col-md-12">
            {{ form.comment }}
        </div>
    </div>
    {{ form.name.as_hidden }}
    {{ form.email.as_hidden }}
    {{ form.gender.as_hidden }}
    <input type="submit" value="Submit feedback" class="btn btn-primary">
</form>

<script>
    $(document).ready(function(){
        $('#feedbackform').submit(function(event){
            event.preventDefault()
            $.ajax({data:$(this).serialize(),
            type:$(this).attr('method'),
            url:$(this).attr('action'),
            success:function(response){
                console.log(response);
                if (response['success']){
                    $('#feedbackmessage').html('<div class="alert alert-success"> Successsfully sent feedback</div>');
                    $('#feedbackform').addClass('hidden');
                };
                if (response['error']){
                    $('#feedbackmessage').html("<div class='alert alert-danger'>"+
                    response['error']['comment']+"</div>");
                }
            },
            error:function (request,status,error){
                console.log(request.responseText);
            }
            })
        })
    })
</script>
{% endblock %}

這裡需要注意的是在JQuery下的Ajax的指令碼中,event.preventDefault方法必須要呼叫,因為這個方法意味著阻止元素髮生預設行為(詳見https://www.runoob.com/jquery/event-preventdefault.html),如果沒有阻止的話,ajax技術就沒有辦法運用,在提交了表單後,頁面直接返回view方法返回的response頁面,而不會根據ajax的邏輯來修改頁面。(ajax簡介:https://www.runoob.com/jquery/jquery-ref-ajax.html)

  • url
#主urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testapp/',include('testapp.urls',namespace='testapp')) #定義名稱空間

]
#app中的urls.py
from django.conf.urls import url 
from testapp import views 
from django.views.generic import TemplateView
app_name='testapp' #定義名稱空間
urlpatterns=[
    url(r'^testDebug',views.testDebug,name='testDebug'),
    url(r'^feedback/$',views.feedback,name='feedback'),
]
  • views.py
def feedback(request):
    if request.POST:
        form=ContactForm(request.POST)
        if form.is_valid():
            return JsonResponse({'success':True})
        else:
            return JsonResponse({'error':form.errors})
    form=ContactForm(initial={'email':'[email protected]','name':'yy','gender':'a'})
    return render(request,'testapp/testAjax.html',{'form':form})
  • forms.py
from django import forms 
class ContactForm(forms.Form):
    name=forms.CharField(required=False)
    email=forms.EmailField(label='Your Email')
    comment=forms.CharField(widget=forms.Textarea)
    gender=forms.ChoiceField(choices=(('a','male'),('b','female'),('c','人妖')))
    def clean_name(self):
        name=self.cleaned_data.get('name','')
        if 'y' not in name:
            raise forms.ValidationError('y not in name')
        return name 

填寫,提交後: