javascript - django 模板无法调用 javascript

标签 javascript html django

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

1) 如果我将脚本标签带到 header 部分,则不会显示任何内容。

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>

ma​​in.js

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

最佳答案

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

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

html:

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

主要.js

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

关于javascript - django 模板无法调用 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720761/

相关文章:

javascript - 如果文本字段为空,则停止表单提交

yui - 为什么YUI的Y.Lang.isNull()和Y.Lang.isUndefined()存在?

python - 使用 django-storages 和 s3 时出现 [Errno 32] Broken pipe

html - Css div 和 ids 问题

Django - XML 中的夹具

python - 我如何收集静态文件?我无法运行这个项目,它会引发错误

javascript - 使用 Handsontable-in-handsontable,如何仅从一列返回值?

javascript - Twitter 提要不显示所有内容,它只是一个链接

html - CSS - 父 div 扩展到子 SVG 之外

html - 防止内容在 flexbox 模态中溢出超出滚动范围