Add AJAX interactivity to Django, without writing Javascript!
在過去的幾年里,JavaScript框架極大地發展,如React和Angular。它們對于web應用很棒,但也增加了Django項目的復雜性。
動態AJAX交互非常棒,在我們的Django項目中如何簡潔地添加它呢?
本文將展示如何只用幾行代碼且不需要寫JavaScript就可以用AJAX增強你的應用(利用Intercooler庫)。例如一個自動完成搜索功能的搜索欄。
準備好依賴
- 我們將使用Intercooler庫,它依賴于jQuery或者超輕量的Zepto。
- 這里從CDN加載它們,將如下兩行加入HTML文件:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://intercoolerreleases-leaddynocom.netdna-ssl.com/intercooler-1.1.1.min.js"></script>
一個基本的搜索表單
- 通常你的Django表單和它的視圖將如下所示:
<form id="form" role="form" action="{% url 'search-submit' %}" method="post">
{% csrf_token %}
<input name="search" id="search" type="search" placeholder="Search"/>
<button type="submit">Submit</button>
</form>
from django.views.generic.base import View
from django.http import HttpResponse
from django.template import loader
class SearchSubmitView(View):
template = 'search_submit.html'
response_message = 'This is the response'
def post(self, request):
template = loader.get_template(self.template)
query = request.POST.get('search', '')
# A simple query for Item objects whose title contain 'query'
items = Item.objects.filter(title__icontains=query)
context = {'title': self.response_message, 'query': query, 'items': items}
rendered_template = template.render(context, request)
return HttpResponse(rendered_template, content_type='text/html')
SearchSubmitView
執行了一個簡單的查詢來查找含有搜索字符的項目,然后渲染結果到search_submit.html
及它的子模板search_results.html
:
<!-- This is the search_submit.html template -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Results</title>
</head>
<body>
{% if query %}
{% include 'search_results.html' %}
{% else %}
<h1 class="h3">Nothing found. <br>Try entering an actual search term.</h1>
{% endif %}
</body>
</html>
<!-- This is the search_results.html sub-template -->
{% if query %}
<h3>You searched for: <i>{{ query }}</i></h3>
<p>{{ title }}</p>
{% if items %}
<ul>
{% for item in items %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
{% endif %}
{% endif %}
為你的表單添加動態行為
- 讓我們用Intercooler的聲明式屬性來更新我們的表格。在下面的代碼片段中,我們為input元素添加了更多的屬性:
- ic-post-to 包含將向其發送AJAX查詢的URL
- ic-trigger-on 是觸發查詢的事件
- ic-trigger-delay 在請求之間增加了一點點延遲
- ic-target 是Intercooler注入搜索結果的元素ID
- 注意該表單仍然保持了原來的post提交功能,然后一個具有
search-result-container
ID的span
標簽被加上:
<form id="form" role="form" action="{% url 'search-submit' %}" method="post">
{% csrf_token %}
<input name="search"
id="search"
type="search"
placeholder="Start typing here"
ic-post-to="{% url 'search-ajax-submit' %}"
ic-trigger-on="keyup changed"
ic-trigger-delay="300ms"
ic-target="#search-result-container"/>
<button type="submit">Search</button>
</form>
<span id="search-result-container"></span>
- 現在我們添加另一個視圖,它繼承自原來的
SearchSubmitView
,只是覆蓋了渲染的模板,變為search_results.html
,即只顯示搜索結果而不是整個頁面。 - 記得添加這個
SearchAjaxSubmitView
到你的url路由(urls.py)。這里我使用了名字search-ajax-submit
來代表它(ic-post-to的屬性值)。
class SearchAjaxSubmitView(SearchSubmitView):
template = 'search_results.html'
response_message = 'This is the AJAX response'
成功了
- 你的搜索結果現在將在你輸入時動態顯示!這種方法的優點在于它通過使用對象繼承和復用現有模板來最小化對現有代碼的重寫。
- 這只是
Intercooler
功能的冰山一角,詳情還請查看文檔http://intercoolerjs.org/docs.html
。