【问题标题】:django javascript not workingdjango javascript不工作
【发布时间】:2016-03-12 08:07:49
【问题描述】:

当我将javascript标签放在index.html文件中时,它运行良好,但当我将它放在静态目录中时,它不起作用,也没有错误。

views.py:

def index(request):
    return render(request, 'index.html')

index.html:(在templates目录中)

{% load staticfiles %}
<script src={% static "/static/jquery.min.js" %}></script>
<script src={% static "/static/script.js" %} type="text/javascript"></script>

<div class="content" id="ajax">

    {% include "svgmap.html" %}

</div>

selection.html:(在templates目录中)

<div style="width:600px;height:300px;border:1px solid red;margin-top:190px;margin-left:50px;">

</div>

并且在 svgmap.html(在templates 目录中)中,我已将onclick="loadDoc()" 添加到每个&lt;path&gt; 标记中。

script.js:(在app目录下,/map/static/)和javascript.min.js在同一个目录下。

<script>
function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
       if (xhttp.readyState == 4 && xhttp.status == 200) {
           document.getElementById("ajax").innerHTML = xhttp.responseText;
       }
    };
    xhttp.open("GET", "/templates/selection", true);
    xhttp.send();
}
</script>

【问题讨论】:

    标签: javascript python django static


    【解决方案1】:

    我会尝试通过执行以下操作来做到这一点:

    <script src="{{STATIC_URL}}<js_folder>/jquery.min.js"></script>
    <script src="{{STATIC_URL}}<js_folder>/script.js"  type="text/javascript"></script>
    

    在哪里

    STATIC_URL = "/path_to_static_files"
    

    在你的例子中可能是:

    "/static/"
    

    这种方法更有用一点,因为您可以有一个外部 CDN URL 也为静态文件、S3 或其他一些服务提供服务。

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2015-01-11
      相关资源
      最近更新 更多