gpt4 book ai didi

javascript - 如何通过ajax将值从django模板发送到 View ?

转载 作者:行者123 更新时间:2023-11-28 02:09:43 24 4
gpt4 key购买 nike

我有一个选择框,可以在更改时调用函数。该函数从“产品”选择框中查找选定的值。
我想将该选定的值扔到我的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>

这是我的观点.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},
)

最佳答案

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

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

我建议研究 Jquery,因为它使 Ajax 和 DOM 操作变得 super 简单。

如果您有 Jquery,那么就像添加到脚本中一样简单:

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

(你也可以在没有 Jquery 的情况下做同样的事情,但它需要更多的争论)

您的test.html文件应包含:

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

关于javascript - 如何通过ajax将值从django模板发送到 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17295838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com