为Django应用简洁地添加AJAX交互

Add AJAX interactivity to Django, without writing Javascript!

在过去的几年里,JavaScript框架极大地发展,如ReactAngular。它们对于web应用很棒,但也增加了Django项目的复杂性。

动态AJAX交互非常棒,在我们的Django项目中如何简洁地添加它呢?

本文将展示如何只用几行代码且不需要写JavaScript就可以用AJAX增强你的应用(利用Intercooler库)。例如一个自动完成搜索功能的搜索栏。

《为Django应用简洁地添加AJAX交互》

准备好依赖

  • 我们将使用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-containerID的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
    原文作者:treelake
    原文地址: https://www.jianshu.com/p/4152b8fe066d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞