在django模板中使用javascript变量

时间:2014-05-27 01:19:38

标签: javascript jquery django django-templates

我有一个自定义模板标记,可通过对SOAP服务的Web调用检索国家/地区列表,并填充html 选择标记。现在我有另一个模板标签,显示给定国家/地区的选项列表,显然,它将国家/地区名称作为参数。因此,只有在html选择标记上触发 onchange 事件后,我才能将国家/地区名称传递给第二个自定义标记,并且我将国家/地区名称作为用户选择的javascript变量。如何将此值传递给自定义模板标记? 这是我的自定义标签

from mezzanine import template
from suds.client import Client
register = template.Library()

@register.as_tag
def get_countries(*args):
    url = 'http://www.sendfromchina.com/shipfee/web_service?wsdl'
    client = Client(url)
    countries = client.service.getCountries()
    countries = map(lambda x: x._enName, countries)
    return countries

@register.as_tag
def get_available_carriers(weight,country,length,width,height):
    url = 'http://www.sendfromchina.com/shipfee/web_service?wsdl'
    client = Client(url)
    rates = client.service.getRates(weight,country,length,width,height)
    rates=map(lambda x: (x._shiptypecode, x._totalfee), rates)
    return rates

这是我的html 选择标记

<select id='countrylist' onchange="getOption(this)">
    {% get_countries as countries %}
    {% for country in countries %}
        <option>{{ country }}</option>
    {% endfor %}
<select>

最后,这是我的javascript

<script type="text/javascript">
function getOption(sel){
    var country = sel.value;
    {% get_available_carriers 1 country 10 10 10 as carriers %}
    console.log('{{ carriers }}')
}
</script>

我似乎无法将 country js变量传递给get_available_carriers标记

非常感谢任何帮助!感谢

2 个答案:

答案 0 :(得分:4)

Django模板构建在服务器端,在页面生成时,而JavaScript则在客户端执行,需要时。 Thus, Django and Javascript can't share objects/data.

在您的网页中,使用当前的Javascript,您将拥有以下内容:

<script type="text/javascript">
function getOption(sel){
    var country = sel.value;
                                // Empty line due to the templatetag
    console.log('')
}
</script>

您需要的是在视图中生成列表并返回已构造的carrier对象。运气好的话,你可以在Javascript中使用它。

这里最好的方法是制作一个AJAX请求来获取这个列表:

def get_available_carriers(request, weight, country, length, width, height):
    url = 'http://www.sendfromchina.com/shipfee/web_service?wsdl'
    client = Client(url)
    rates = client.service.getRates(weight,country,length,width,height)
    rates=map(lambda x: (x._shiptypecode, x._totalfee), rates)

    return json.dumps(rates)

并使用jQuery获取它(如果您正在使用它):

    $.get('{% url "get_available_carriers" 1 country 10 10 10 %}', function(data){
        console.log(data);
    });

不要忘记在我的示例中使用get_available_carriers定义网址格式。

答案 1 :(得分:3)

您没有将值从javascript函数传递到django模板标记。但在这种情况下,您可以使用ajax调用。

http://www.tangowithdjango.com/book/chapters/ajax.html

https://bradmontgomery.net/blog/2008/11/24/a-simple-django-example-with-ajax/

更新

看到这一点,你就能明白发生了什么。

How to pass javascript variable to django custom filter

希望这是有用的想法。