【问题标题】:Django calling url in javascriptDjango在javascript中调用url
【发布时间】:2016-06-10 17:24:55
【问题描述】:

我正在做我的 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)

此 location.href 重定向到错误的位置。它实际上将“{% url 'index' %}”放在 URL 中。

感谢您的帮助!

【问题讨论】:

  • 这段代码是否在 django-template 中使用?
  • 嗨,这是在 static/timecounter.js 中,我从我的 html 调用它
  • @chazefate 你的模板标签{% url (显然)将不起作用,除非它在 ​​Django 视图/模板中使用。请改用您网站的绝对网址。
  • 你想重定向到根目录?你为什么不直接使用/
  • 正如@ilse2005 所说,您需要重定向到/或索引所在的位置。模板标签仅在渲染页面时由 django 解释。 Javascript在浏览器中运行,与django完全无关

标签: javascript django redirect django-templates url-redirection


【解决方案1】:

由于您的代码是静态的并且没有被 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)

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2016-09-15
    • 2013-02-19
    • 2021-07-09
    • 2013-01-23
    • 2012-08-07
    • 2012-10-31
    • 2013-06-20
    • 2020-09-07
    相关资源
    最近更新 更多