更新DOM而不重新加载Django中的页面 [英] Update DOM without reloading the page in Django

查看:126
本文介绍了更新DOM而不重新加载Django中的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DOM中有两个选择列表,第一个是在视图的方法加载页面时在URL加载期间填充的。第二个选择列表的内容取决于用户在第一个选择列表中选择的内容。
当用户在第一个选择列表中进行选择时,如何在事件中绑定python方法,在python中进行一些操作,返回要在第二个选择列表中显示的vallues列表,然后在不刷新的情况下填充它

I have two picklists in DOM, first is populated during loading of URL when a method in views loads the page. Second picklist's content depends on what user selects in first picklist. How do I bind python method to event when user makes a selection in first picklist, make some manipulations in python, return a list of vallues I'd like to be displayed in the second picklist and then populate it without refreshing the page?

我的模板如下:

{% block content %}

{% if list_of_events %}
    <form>
        <select>
            {% for event in list_of_events %}
                <option value="name">{{ event.module }}</option>
            {% endfor %}
        </select>
    </form>

{% else %}
    <p>No events available now.</p>
{% endif %}

下一个条件正在等待first_selection参数,该参数应返回给

Next condition is waiting for first_selection argument which should be returned to template after user selects a value in first picklist.

{% if first_selection %}
    <form>
        <select>
            {% for room in list_of_rooms %}
                <option value="name">{{ room.id }}</option>
            {% endfor %}
        </select>
    </form>
{% endif %}

<input type="submit" value="Submit">

{% endblock %}

我的视图.py 方法如下:

def events(request):
try:
    list_of_events = Event.objects.all()
except:
    raise Http404('Something\'s wrong with events page loader')
return render(request, 'web_service/schedule.html', {
    'list_of_events': list_of_events

})


推荐答案

在Django中,至少目前没有直接方法从 python 方法> html 模板而不刷新页面。

In Django, at least now, there's no direct way to dynamically call python method from html template without refreshing the page.

调用 python 方法并查看它的模板效果而无需刷新页面,您将需要一些 JS ,专用的 url 模式和一个视图。它不像调用实例方法那样简单,但并不像看起来那样难。

To call python method and see it's effect in template without refreshing the page you'll need a bit of JS, dedicated url pattern and a view. It’s not as simple as calling instance method, but not as hard as it may seem.

下面的示例演示了如何响应按钮单击,将一些数据发送到视图,然后将结果返回模板,而无需刷新 DOM

The example below is a demonstration how to respond to a button click, send some data to a view and return the result to template without refreshing DOM.

从模板调用python代码的唯一方法与我们与<$相关的方式相同c $ c> url ,这意味着我们必须创建新的 url模式。然后调用必要的 view 并将响应作为 JsonResponse 返回到模板。

The only way to call python code from template is relate to in the same way as we relate to url, this means we have to create new url pattern. Then call necessary view and return response to template as JsonResponse.

注意:请确保在< body> jquery $ c>标签。

Note: make sure to import jquery at the inside bottom of your <body> tag.

首先,我们需要创建响应器,该响应器将处理按钮单击并创建 AJAX 请求连接到视图的网址。 AJAX请求 input 作为参数传递给我们的网址格式,这意味着该参数将传递给Django 视图。如果从我们调用 view 中返回了某些内容,则数据将以成功闭包形式解压缩。

First of all we need to create responder which will handle button click and create AJAX request to url connected to view. AJAX request passes input as parameter to our url pattern, meaning this parameter will be passed to django view. If something returns from our call to view then data is being unpacked in success closure.

比方说我们的模板如下:

Let’s say our template looks like this:

<input type="text" id="user-input" autofocus=""><br>
<button type="button" id="sender">Send data</button><br>
<p id="p-text">foo bar</p>

脚本处理点击和请求的方式如下:

Script handling clicks and request looks like this:

<script>

$("#sender").click(function () {
    var input = $('#user-input').val();

    $.ajax({
        url: '{% url 'get_response' %}',
        data: {
          'inputValue': input
        },
        dataType: 'json',
        success: function (data) {
          document.getElementById('p-text').innerHTML = data["response"];
        }
      });
    });

</script>

urls.py需要新的模式:

New pattern is needed in urls.py:

urlpatterns = [
    ...
    url(r'^ajax/get_response/$', views.answer_me, name='get_response')
    ...
]

注意:网址的code> ajax / 部分以及网址模式本身的路径对如何处理此调用没有影响。它可以是您想要的任何内容,例如: ^ foo / bar / $

Note: the ajax/ part of url and path of url pattern itself has no influence on how this call is handled. It can be anything you want, for example: ^foo/bar/$.

最后一步是添加响应Django 视图。这个简单的示例返回带有一些附加文本的输入,但是通常在这里您可以调用其他python方法并执行所需的操作:

Last step is adding responding Django view. This simple example returns the input with some additional text, but generally this is the place where you can call other python methods and do whatever you want:

def answer_me(request):
    user_input = request.GET.get('inputValue')
    data = {'response': f'You typed: {user_input}'}
    return JsonResponse(data)

这篇关于更新DOM而不重新加载Django中的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆