Twisted - 无需重新加载更新网页内容
这里有一段代码,可以在网页上显示当前时间:
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import time
class ClockPage(Resource):
isLeaf = True
def render_GET(self, request):
return "<html><body>%s</body></html>" % (time.ctime(),)
resource = ClockPage()
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()
我该如何修改这段代码,让它每秒更新一次显示的时间,而不需要重新加载页面呢?我应该使用JavaScript(比如ajax或jquery)定时发送GET请求,还是可以在Python代码中实现?
谢谢。
1 个回答
1
在返回的HTML中添加
<head>
<meta http-equiv="refresh" content="5">
</head>
以便每5秒重新加载一次。
更新
如果你想更新页面的一部分,就需要使用AJAX请求来获取部分页面的数据:
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import time
page = """
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="timer">
%s
</div>
</body>
<script>
function update_timer() {
$.get("/timer", function(data) {
$("#timer").replaceWith(data);
window.setTimeout(update_timer, 1000);
});
}
window.setTimeout(update_timer, 1000);
</script>
</html>
"""
class ClockPage(Resource):
isLeaf = True
def render_GET(self, request):
return page % (time.ctime(),)
class ClockSubelem(Resource):
isLeaf = True
def render_GET(self, request):
return str(time.ctime())
resource = ClockPage()
timer = ClockSubelem()
resource.putChild("timer", timer)
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()