Mik*_* IT 2 html javascript 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>
Run Code Online (Sandbox Code Playgroud)
main.js
function postData ()
{
$.post('/newproduct', {name:'New Product JS', price:555, });
};
Run Code Online (Sandbox Code Playgroud)
您已经postData在HTML中对引用进行了硬编码,但是在定义之前已经使用过它,因为直到页面末尾才加载JS.
您可以通过将脚本移动到HTML的顶部来解决此问题,但最好不要在HTML中直接使用JS.相反,您的脚本本身应该使用jQuery dom-ready功能将自身绑定到按钮事件.
HTML:
<h2>Please enter product details:</h2>
<button id="my_button">Send Post</button>
Run Code Online (Sandbox Code Playgroud)
main.js
$(function() {
$('#my_button').click(function() {
$.post('/newproduct', {name:'New Product JS', price:555, });
});
});
Run Code Online (Sandbox Code Playgroud)