Django 在 javascript 中调用 url

cha*_*ate 3 javascript django redirect django-templates url-redirection

我正在做我的 django 项目,但我找不到如何从 javascript 函数调用我的网站的答案。

  var time = 5;
  setInterval(function() {
    if(time > 0) {
      document.getElementById("timecounter").innerHTML = "You will be redirected in "
      + time + " seconds. If not then ";
      time--;
    } else {
      location.href="{% url 'index' %}"
    }

  },1000)
Run Code Online (Sandbox Code Playgroud)

这个 location.href 重定向到错误的地方。它的字面意思是将“{% url 'index' %}”放在 URL 中。

谢谢你的帮助!

ils*_*005 6

由于您的代码是静态的并且不是由 django 处理的,因此您不能使用模板标签。将您的代码更改为:

var time = 5;
  setInterval(function() {
    if(time > 0) {
      document.getElementById("timecounter").innerHTML = "You will be redirected in "
      + time + " seconds. If not then ";
      time--;
    } else {
      location.href="/" //this will redirect to your index
    }

  },1000)
Run Code Online (Sandbox Code Playgroud)