Django和她的朋友们程序员首页投稿(暂停使用,暂停投稿)

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

2017-03-30  本文已影响1988人  treelake

Add AJAX interactivity to Django, without writing Javascript!

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

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

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

准备好依赖

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

一个基本的搜索表单

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

为你的表单添加动态行为

<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>
class SearchAjaxSubmitView(SearchSubmitView):
    template = 'search_results.html'
    response_message = 'This is the AJAX response'

成功了

上一篇 下一篇

猜你喜欢

热点阅读