使用turn.js定期刷新图书的动态页面

Periodic refresh of a book's dynamic pages using turn.js

本文关键字:动态 刷新 turn js 使用      更新时间:2023-09-26

我使用这里提供的示例创建了一个使用turn.js查看的动态生成内容的示例。

这是目前为止我写的代码的一部分:

<body>
   <div id="paper">
   </div>
</body>
<script type="text/javascript">
    $(window).ready(function() {
        $('#paper').turn({pages: 12});
    });
    $('#paper').bind('turning', function(e, page) {
          var range = $(this).turn('range', page);
          for (page = range[0]; page<=range[1]; page++)
            addPage(page, $(this));
        });
    function addPage(page, book) {
           // Check if the page is not in the book
          if (!book.turn('hasPage', page)) {
            // Create an element for this page
            var element = $('<div />').html('Loading…');
            // Add the page
            book.turn('addPage', element, page);
            // Get the data for this page   
           $.ajax({url: "getPage?filename=abcd&page="+page})
             .done(function(data) {
               element.html(data);
             });
           }
        }
</script>

getPage是一个jsp,它根据ajax请求返回<div class="page"><img src="docs/local/abcd_1.png" alt="" /></div>或任何其他页码。

我的问题是,png的请求可能是或可能不是在请求的时候在web服务器上可用。它们将在几秒钟(有时是很多秒)后变得可用。所以我希望能够显示一些默认的"Loading…"类型的内容,如果png不可用,并定期刷新(即每x秒),直到实际的png可用。如果需要,更改getPage的输出没有问题。

我自己做了以下修改,成功地完成了这项工作:

getPage现在返回<div class="loader"><img src="docs/local/ajax-loader.gif" alt="" /></div>如果请求的png不可用。

在调用页面中,我已经更改了我的代码来检查'loader'字符串,如果发现(这意味着png不可用),那么我调用setTimeout,在给定的时间后重试获取图像:

<body>
   <div id="paper">
   </div>
</body>
<script type="text/javascript">
    $(window).ready(function() {
        $('#paper').turn({pages: <s:property value='pages'/>});
    });
    $('#paper').bind('turning', function(e, page) {
          var range = $(this).turn('range', page);
          for (page = range[0]; page<=range[1]; page++)
            addPage(page, $(this));
        });
    function addPage(page, book) {
           // Check if the page is not in the book
          if (!book.turn('hasPage', page)) {
            // Create an element for this page
            var element = $('<div />').html('Loading…');
            // Add the page
            book.turn('addPage', element, page);
            // Get the data for this page   
            refreshPage(element,page);
          }
        }
    function refreshPage( element, page )
    {
           $.ajax({url: "getPage?filename=<s:property value='filename'/>&page="+page})
             .done(function(data) {
               if( data.indexOf( "loader") > -1 )
               {
                   setTimeout(function() {
                       refreshPage(element,page);
                    }, 5000);
               }
               element.html(data);
             });
    }

也许有更好的方法来实现这一点,但至少它有效。