在django模板中使用javascript变量

dav*_*yan 13 javascript django jquery 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
Run Code Online (Sandbox Code Playgroud)

这是我的html 选择标记

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

最后,这是我的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>
Run Code Online (Sandbox Code Playgroud)

我似乎无法将country js变量传递给get_available_carrierstag

任何帮助都非常感谢!谢谢

Max*_*ant 5

Django模板建立在服务器端,在页面生成时,而JavaScript在客户端执行(需要时)。因此,Django和Javascript无法共享对象/数据。

在页面中,使用当前的Javascript,您将看到类似以下内容:

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

您需要的是在视图中生成列表并返回一个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)
Run Code Online (Sandbox Code Playgroud)

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

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

get_available_carriers在我的示例中,请不要忘记定义URL模式。


dha*_*ana 4

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

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

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

更新:

看到这里你就明白是怎么回事了。

如何将 javascript 变量传递给 django 自定义过滤器

希望这是有用的想法。