【问题标题】:How to send values via ajax from django template to views?如何通过 ajax 将值从 django 模板发送到视图?
【发布时间】:2013-06-22 03:53:02
【问题描述】:

我有一个选择框,它在更改时调用一个函数。该函数从“产品”选择框中查找选定的值。
我想将该选定的值扔给我的views.py,在某些操作后返回数据列表并填充目的地的选择框。
我想为此目的使用ajax。请帮忙。

我的代码如下所示:

<script type="text/javascript">
    function select_value()
    {
        var e = document.getElementById("Product");
        var prod = e.options[e.selectedIndex].text
        console.log(prod)
    }
</script>

这是我的选择框的样子:

<table>
    <tr>
        <td>
            <select id="Product" onChange="select_value();">
                {% for products in product_name_list %}
                    <option>{{products|safe}}</option>
                {% endfor %}
            </select>
        </td>
        <td>
            <select id="dest">
                {% for des in destinations_name_list %}
                    <option>{{des|safe}}</option>
                {% endfor %}
            </select>
        </td>
     </tr>
</table>

这是我的views.py:

def selection_filter(request,prod):
    destination_objs = Destination.objects.filter(product=prod)
    destination_name = destination_objs.values_list('name')
    destination_name_list = []
    for iter_name in destination_name:
        destination_name_list.append(iter_name[0].encode('utf-8'))

    return render_to_response('temp/test.html',
                {"destination_name_list"    :   destination_name_list},
                )

【问题讨论】:

    标签: javascript ajax django-templates


    【解决方案1】:

    我认为您可能会误解的一点是,您的整个页面的 Django 模板不会“神奇地”重新呈现。在 Django 的标准模型-视图-模板范例中,模板仅在初始请求时呈现一次。按照您编写它的方式,除非有默认产品选择,否则您将在第一次渲染中看到一个尴尬的空 &lt;select&gt;。但忽略这一点......

    对于这样的问题,您需要两个视图:一个用于呈现整个页面,另一个用于提供 Ajax 响应。第二种视图有两个主要选项:1) 返回 JSON 以供脚本响应后解释/呈现,或 2) 返回完全呈现的 HTML 片段以直接插入 DOM。在这种情况下,我只会选择选项 2。

    我建议研究 Jquery,因为它使 Ajax 和 DOM 操作超级简单。

    如果你有 Jquery,它就像添加到你的脚本一样简单:

    $.get('/destinations/' + prod)
    .done(function (html) {
        $(#dest).html(html);
    });
    

    (你也可以不使用 Jquery 做同样的事情,但需要更多的争论)

    您的test.html 文件应包含:

    {% for des in destinations_name_list %}
        <option>{{des|safe}}</option>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 2022-01-17
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      相关资源
      最近更新 更多