Javascript 我应该将document.title放置在脚本中的何处以每xx毫秒更改一次标题?
我有一个脚本,可以刷新一些Javascript 我应该将document.title放置在脚本中的何处以每xx毫秒更改一次标题?,javascript,jquery,ajax,flask,jinja2,Javascript,Jquery,Ajax,Flask,Jinja2,我有一个脚本,可以刷新一些#id 我还想更新包含一些flask/jinja2的页面标题 我试着把document.title={%block title%}({{online_num}})放到在线玩家{%endblock%}脚本中的不同位置,但我无法让它工作 我真的不知道javascript/jquery/ajax,所以它是反复试验的,只有错误:) 有人能帮助我在哪里或如何插入文档。title,以便每隔15000毫秒使用#main和#count进行刷新/更新 剧本: <script typ
#id
我还想更新包含一些flask/jinja2的页面标题
我试着把document.title={%block title%}({{online_num}})放到在线玩家{%endblock%}代码>脚本中的不同位置,但我无法让它工作
我真的不知道javascript/jquery/ajax,所以它是反复试验的,只有错误:)
有人能帮助我在哪里或如何插入文档。title
,以便每隔15000毫秒使用#main
和#count
进行刷新/更新
剧本:
<script type="text/javascript">
$(document).ready(function() { /// Wait till page is loaded
setInterval(timingLoad, 15000);
function timingLoad() {
$.get().done(doc => {
$("#main").html($(" #main", doc))
$("#count").html($(" #count", doc))
});
}
}); //// End of Wait till page is loaded
</script>
$(document).ready(function(){///等待页面加载
设置间隔(定时负载,15000);
函数计时加载(){
$.get().done(doc=>{
$(“#main”).html($(“#main”,doc))
$(“#count”).html($(“#count”,doc))
});
}
}); //// 等待页面加载结束
您应该区分代码何时执行。Jinja2语句在页面提交到客户端/浏览器之前在服务器端呈现。Javascript发生在浏览器中,能够动态更改页面。AJAX可用于随后在后台加载数据或将数据发送到服务器。正如您在代码中建议的那样,混合使用jinja和javascript是不可能的。您应该使用javascript加载数据,就像更新元素一样,还应该重置标题的内容
服务器的示例有两个端点,第一个端点负责发送实际页面。第二个端点以JSON格式发送请求的更新
import random
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', online_num=0)
@app.route('/stats')
def stats():
# Generate random integers between 0 and 10.
num = random.randint(0, 10)
return jsonify(count=num)
将在浏览器中加载当前图形并定期更新标题。
jQuery提供了许多不同的函数来检索数据。这些是函数的简化。在下文中,我使用了函数的一个特殊变体,它针对JSON传输进行了优化。调用该函数
{%extends“base.html”%}
{%block title%}{{online_num}}玩家在线{%endblock%}
{%block scripts%}
$(文档).ready(函数(){
setInterval(函数(){
$.getJSON(“/stats”)
.done(数据=>{
让msg=data.count==1?'Player online':'Player online';
document.title=`${data.count}${msg}`;
});
}, 15000);
});
{%endblock%}
{% extends "base.html" %}
{% block title %}{{ online_num }} Players online{% endblock %}
{% block scripts %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$.getJSON('/stats')
.done(data => {
let msg = data.count == 1 ? 'Player online' : 'Players online';
document.title = `${data.count} ${msg}`;
});
}, 15000);
});
</script>
{% endblock %}