尝试在html中使用脚本变量
我正在尝试使用我从 ajax 更新函数中获取的 json 中的值来设置 html 中输入的默认值。该值是从 ajax 正确返回的,但我在 html 中使用它时遇到了麻烦。
我创建了一个“命名空间”来包含我的变量。如何在 html 中使用变量?请注意,“.innerHTML”和“.value”不起作用,因为(我猜测)这是一个带有最小、最大、步长的输入?如果我将 {{ myNamespace.low_pump_speed_value }} 替换为可接受的数字(800 到 1500 之间),则代码将按预期工作。
我收到以下错误:
jinja2.exceptions.UndefinedError: 'myNamespace' is undefined
这是 html 文件:
<body>
<script>
myNamespace = { low_pump_speed_value: 850,
high_pump_speed_value: 950,
chlorine_percent_value: 1050};
document.write(myNamespace)
console.log("second", myNamespace)
</script>
<label for="low-pump-speed-id">Low Pump Speed:</label>
<input type="number" id="low-pump-speed-id" name="low-pump-speed-id" step="50" min="800" max="1500" required value="{{ myNamespace.low_pump_speed_value }}">
</body>
<script type="text/javascript">
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
myNamespace.low_pump_speed_value = response["pump"]['low-speed'];
},
error: function(error) {
console.log(error);
}
})}, 250);
</script>
I am trying to set the default value of an input in html with one that I get in the json from my ajax update function. The value is getting back from the ajax correctly, but I am having a devil of a time using it in the html.
I have created a "namespace" to contain my variables. How do I use the variables in my html? Note that ".innerHTML" and ".value" don't work because (I'm guessing) this is an input with min, max, step? If I replace {{ myNamespace.low_pump_speed_value }} with an acceptable number (between 800 and 1500), the code works as expected.
I am getting the following error:
jinja2.exceptions.UndefinedError: 'myNamespace' is undefined
Here is the html file:
<body>
<script>
myNamespace = { low_pump_speed_value: 850,
high_pump_speed_value: 950,
chlorine_percent_value: 1050};
document.write(myNamespace)
console.log("second", myNamespace)
</script>
<label for="low-pump-speed-id">Low Pump Speed:</label>
<input type="number" id="low-pump-speed-id" name="low-pump-speed-id" step="50" min="800" max="1500" required value="{{ myNamespace.low_pump_speed_value }}">
</body>
<script type="text/javascript">
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
myNamespace.low_pump_speed_value = response["pump"]['low-speed'];
},
error: function(error) {
console.log(error);
}
})}, 250);
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 max..min 范围内的值,例如:
然后,您可以将此值分配给输入字段,如下所示:
You should use values within the max..min range, for example:
Then, you can assign this value to the input field as follows:
感谢 (bedankt) www.admiraalit.nl,现在可以使用:
我必须相信我所做的事情是愚蠢的,因为我以为我是这样开始的,最后却陷入了困境。
Thanks (bedankt) to www.admiraalit.nl, this is now working:
I have to believe that it was something stoopid I was doing as I thought I started out this way and just wound up in the weeds.