2016-07-06 89 views
2

嘿,我有点新,但我目前正在编写一个小游戏,并且我有一个使用jquery,css和php的健康栏。我使用mysql查询从数据库中获取健康值,并且只有当我重新加载页面时才有效。我希望健康栏的价值不断更新,我希望每秒达到x秒。如何在不重新加载页面的情况下刷新div和mysql代码

<script> 
 
    function UpdateStats() { 
 
    $.getJSON('demo1.php', function(stats) { 
 
     $('#pbar_innerdiv').animate({ 
 
     width: (stats.health) + '%' 
 
     }, 200); 
 
    }); 
 

 
    }, 1000; < /script>
#pbar_outerdiv { 
 
    margin-top: 5px; 
 
    margin-left: 90px; 
 
} 
 
#pbar_innertext { 
 
    margin-top: 6px; 
 
    margin-left: 7px; 
 
}
<div id="pbar_outerdiv" style="width: 580px; height: 32px; border: 1px solid white; z-index: 1; position: relative; border-radius: 2px; -moz-border-radius: 5px;"> 
 
    <div id="pbar_innerdiv" style="background-color: maroon; z-index: 2; height: 100%; width: <?php echo $health;?>%;"></div> 
 
    <div id="pbar_innertext" style="z-index: 3; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color: white; font-weight: bold; text-align: center;"> 
 
    <?php echo $health;?>/100</div> 
 
</div>

+0

这就是php的样子 $?UserStats = mysql_query(“SELECT health,hunger,energy, ['ID']。”'”); $ UserStats = mysql_fetch_assoc($ UserStats); echo json_encode($ UserStats); ?> –

+0

你的setTimeout JS函数在哪里? “,1000”在这里没有意义。 – Aviator

回答

0

改变你这样的脚本

<script> 
     function UpdateStats() { 
     $.getJSON('demo1.php', function(stats) { 
      $('#pbar_innerdiv').animate({ 
      width: (stats.health) + '%' 
      }, 200); 
     }); 

     setTimeout(function(){UpdateStats()}, 3000); 
     } 

    UpdateStats();  

     < /script> 

这一个是更好然后setInterval的,它会调用第二次迭代时,第一个是完整的。希望它会帮助

explanation:首先它会在UpdateStats()完成后调用UpdateStats()函数,然后等待3秒钟,然后它会调用第二次迭代。这个将重复执行

相关问题