首页 > 解决方案 > 通过带有参数的javascript调用django url

问题描述

这是我传递参数的javascript函数,使用警报我检查了该函数是否正在获取我想要的参数,但我无法在django url中传递它们,否则给出一个url有效但不带参数的字符串。

      function myFunction(a) {
      var v = a.value;
      alert(v);
      location.href="{% url 'new_event' v %}"; //does not works
      location.href="{% url 'new_event' 'string' %}"; //works
      }

我已经检查了获取的值是我想要的字符串但是如何传递它?

标签: javascriptdjango

解决方案


请试试这个:

    function myFunction(a) {
        var v = a.value;
        alert(v);
        location.href="{% url 'new_event' v %}"; // this will not work because your django **url** filter is pre-processed on your server while your javascript variable is processed on **client**
        // if you want your variable v to be dynamic, you need to include it in your django's view **context**
        location.href="{% url 'new_event' 'string' %}"; //works
    }

    // include in your views.py
    context['v'] = 'some-string'

    // template.html
    <script>
        function myFunction(a) {
            var v = '{{ v }}'; // javascript variable v
            alert(v);
            location.href="{% url 'new_event' v %}"; // django context variable v
        }
    </script>

推荐阅读