扭曲 - 更新网页内容而无需重新加载

时间:2014-09-07 11:38:57

标签: python http 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 个答案:

答案 0 :(得分:1)

添加

<head>
    <meta http-equiv="refresh" content="5">
</head>

返回html,每5秒重新加载一次。

<强> UPD

对于部分页面更新,您需要对部分页面数据进行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()
相关问题