【问题标题】:Twisted - Update web page content without reloadingTwisted - 无需重新加载即可更新网页内容
【发布时间】:2014-09-07 11:38:56
【问题描述】:

网页上有显示当前时间的代码:

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 代码中执行?

谢谢。

【问题讨论】:

    标签: python http twisted


    【解决方案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()
    

    【讨论】:

    • > 无需重新加载页面
    猜你喜欢
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多