如何刷新我的网页的特定部分?

时间:2013-01-13 11:06:42

标签: ajax jquery

我有一个自动刷新按钮,当按钮打开时,我的网页的某个特定部分应该刷新。例如,如果我有一个DIV,当按钮打开时,此DIV中的内容应该重新加载。如果按钮为OFF,则DIV应保持不变。

只有当“自动刷新”按钮为“开”时,我才会进行编码。是否可以刷新网页的特定部分?

这是我的编码: -

var int=self.setInterval(function(){refreshPage()},60000);
$(document).ready(function() {
   var hashTag = window.location.href.split('#');
   if (hashTag[1] == 'reload') {
      $('#refresh').addClass('refresh-on').html('');  
   }
   $('#refresh').on('click', function() { 
      $(this).toggleClass('refresh-on'); 
      if ($(this).hasClass('refresh-on'))
         $(this).html('Refresh On');
      else 
         $(this).html('Refresh Off');
   });
});

function refreshPage() {
   if ($('#refresh').hasClass('refresh-on')) {
      location.hash = 'reload';
      window.location.reload();
   } else
     location.hash = '';
}

2 个答案:

答案 0 :(得分:2)

如果您可以在单独的页面中保存要刷新的内容,则可以使用简单的jquery的load()方法。

将要刷新的内容放在'content.php'

$("#refreshDIV").load("content.php");

您可以在需要时调用此方法,并且可以动态加载。

答案 1 :(得分:0)

实际上,jquery的load()方法是用外部脚本更新分离内容的好方法...
下面是一个包含2个div的小html页面的示例 一个是每1秒刷新一次,另外每3秒刷新一次...... Div正在使用refreshDiv函数进行刷新。
refreshDiv函数有3个参数:

  • div_id :这是您要刷新的div的ID;
  • script_file :要启动以刷新div的脚本; (scripts / directory);
  • 数据:一些数据通过GET方法传递给脚本(PHP);

    <html>
    <head>
       <title>Stack OverFlow - 14302842</title>
       <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
       <script type="text/javascript">
          function refreshDiv(div_id, script_file, data) {
             var today = new Date();
             $("#"+div_id).load("scripts/"+script_file+"?_"+Math.random()+"&data="+data);           
          }
    
          $(document).ready(function () {
              refreshDiv('div1','ls.php','/tmp');
              refreshDiv('div2','ls.php','/home');
    
              setInterval(function() {
                  // Do something every 3 seconds
                  refreshDiv('div1','ls.php','/tmp');
              }, 3000);
    
              setInterval(function() {
                 // Do something every 1 seconds
                 refreshDiv('div2','ls.php','/home');
              }, 1000);
    
          });
       </script>
    </head>
    <body>
        <div id="div1" style="color: #F00; border: 1px solid #F00; text-align: center;">Some Text</div>
        <div id="div2" style="color: #00F; border: 1px solid #00F; text-align: center;">Some Text</div>
    </body>
    </html>
    
相关问题