【问题标题】:How to pass static js file in django template script?如何在 django 模板脚本中传递静态 js 文件?
【发布时间】:2021-07-07 04:50:33
【问题描述】:

我想将代码中存在的静态文件json加载到js中以托管swagger。

我的 index.html:

<HTML>
<head>
{% load static %}
</head>
<body>
<script src="{% static "js/script1" %}"></script>
<script>
var json_contents = // Use the static json `js/json1.json` in here?
</script>
</body>
</html>

以上怎么做?

【问题讨论】:

标签: javascript django django-templates django-staticfiles


【解决方案1】:

你拼错了static模板标签

{% load static %} <!-- not "staticfiles" -->
<!DOCTYPE html>
<HTML>
  <body>
  <script src="{% static "js/script1.js" %}"></script> <!-- missed .js extention -->
  <script>

    async function load() {
        let url = '{% static "js/json1.json" %}';
        let json_contents = await (await fetch(url)).json();
        console.log(json_contents);
    }
    load();

  </script>
  </body>
</html>

Documentation: Configuring static files

【讨论】:

  • 知道了。但我要问的问题不是那个。它是如何在脚本中包含静态 json1.json。不过,我会改变问题
  • 你在用jquery吗?
  • 没有。我目前正在使用香草 javascript。
  • 这个 JSON 文件是驻留在本地服务器还是外部服务器中?
  • 它存在于静态文件夹中
猜你喜欢
  • 2011-09-17
  • 2013-01-23
  • 1970-01-01
  • 2023-03-29
  • 2020-11-28
  • 1970-01-01
  • 2020-11-13
  • 2013-06-18
  • 1970-01-01
相关资源
最近更新 更多