django模板无法调用javascript

时间:2016-11-21 12:56:47

标签: javascript html django

我有以下django模板,我在其中定义了一个按钮,以便调用我添加到页面中的javascript函数,如下所示。我有以下问题:

1)如果我将脚本标签带到标题部分,则显示无效。

2)如果按下按钮,我会收到未定义的错误消息。 (未捕获的ReferenceError:postData)。

我在这里忙什么?

非常感谢, 麦克

newproduct.html

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>





<title>New Product</title>
</head>  
<body>
<p>Hellow</p>
<a href="/">Back</a>

    <h2>Please enter product details:</h2>
    <button onclick="postData();">Send Post</button>


<form action="http://127.0.0.1:8000/newproduct/" method="post">
    <p>{{ message }}</p>
        {% csrf_token %}
        {{ form.as_p }}

    <input type="submit"/>
</form>


<script src="bower_components/jquery/src/jquery.js" type="text/javascript"/>
<script src="scripts/main.js" />

</body>
</html>

main.js

function postData ()
{
    $.post('/newproduct', {name:'New Product JS', price:555, });
};

2 个答案:

答案 0 :(得分:5)

您已经在HTML中对postData的引用进行了硬编码,但是在您定义之前已经使用过它,因为JS直到加载为止页面的末尾。

您可以通过将脚本移动到HTML的顶部来解决此问题,但最好不要在HTML中直接使用JS。相反,您的脚本本身应该使用jQuery dom-ready功能将自身绑定到按钮事件。

HTML:

<h2>Please enter product details:</h2>
<button id="my_button">Send Post</button>

main.js

$(function() {
  $('#my_button').click(function() {
    $.post('/newproduct', {name:'New Product JS', price:555, });
  });
});

答案 1 :(得分:1)

也许你在处理路径网址时遇到问题,而是使用完整路径,尝试类似:

{% static ‘path/to/file’ %}

在你的settings.py

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

请记住,您的静态文件目录设置在项目的同一级别。