【问题标题】:How typing the correct path to my json file inside a javascript file如何在 javascript 文件中键入我的 json 文件的正确路径
【发布时间】:2018-02-08 20:53:53
【问题描述】:

python 3.6.4,django 2.0

我有一个index.html,它加载了这个javascript文件script.js,在里面我有问题输入一个json文件data.json的正确路径。

现在显示的 index.html 没有来自 data.json 的信息,我使用的是 XmlHttpRequest 对象。

function makeRequest(url){
...
    http_request = new XMLHttpRequest();
    http_request.open('GET', url, true);
}
...
window.onload = function(){
    makeRequest("here/have/problems");
}

我的文件树

在 index.html 中我正在使用

{% load static %}
...
<script src="{% static 'bar/scripts/script.js' %}"></script>

效果很好,然后在 script.js 中尝试输入“bar/data/data.json”但不起作用。请以正确的方式指导我解决此问题。

【问题讨论】:

    标签: javascript json django xmlhttprequest


    【解决方案1】:

    您需要使用完整路径,包括前导斜杠 - 所以“/static/bar/data/data.json”。

    避免硬编码完整路径的一种可能做法是使用{% static %} 标记在模板内的独立&lt;script&gt; 块中设置全局JS 变量。

    【讨论】:

      【解决方案2】:

      要上一级目录,请使用两个点,后跟一个斜杠(“../”)。您需要上两级目录才能离开templates/bar/

      {% static '../../bar/scripts/script.js'%}
      

      【讨论】:

      • templates/bar 在这里根本不相关,因为它完全在 Django 应用程序内部。相关的是提供视图的 URL。
      猜你喜欢
      • 2021-09-22
      • 2011-05-16
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多