在 PHP 中获取数据时等待动画


waiting animation while fetching data in PHP

我有一个带有加载动画的 gif。在我的代码中,我使用 mysqli_query() 从服务器获取数据。因为,表格非常大,我需要时间才能看到结果。

我正在尝试在 PHP 函数获取数据时显示"加载"动画。

这是我的PHP代码,

if (isset($_GET['variable'])) {
    $_SESSION['variable'] = $_GET['variable'];
    $results = mysqli_query($mysqli,"select q1.variable, t3.label, q1.numvalue, description, num_cases from (select variable, numvalue, count(variable) as num_cases from nhws.num_all_{$_SESSION['country']} where variable = '{$_SESSION['variable']}' group by variable, numvalue) q1 inner join (select * from nhws.luvalues where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t2 on q1.numvalue=t2.numvalue inner join (select * from nhws.luvariables where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t3 on q1.variable=t3.variable;");
    echo "<h5>Counts</h5>";
    echo '<div id="container" ><img src="ajax-loader.gif" alt="Searching" /></div>';
    if ($results->num_rows > 0) {
         echo "<table><tr><th>Variable</th><th>label</th><th>Numvalue</th><th>Description</th><th>Num Cases</th></tr>";
         // output data of each row
         while($row = $results->fetch_assoc()) {
                echo "<tr><td>" . $row["variable"]. "</td><td>" . $row["label"]. "</td><td>" . $row["numvalue"]. "</td><td>" . $row["description"]. "</td><td>" . $row["num_cases"]. "</td></tr>";
         }
         echo "</table>";
    } else {echo "0 results";}
}

我假设mysqli_query()函数需要时间,因为在我的浏览器中,它在右下角显示"等待(服务器的 IP 地址)"

我用 AJAX 尝试了几种方法,但在网站等待服务器时它不起作用。当网站等待自己而不是查询时,它确实有效。

这是我的剧本,

<script>
function makeLoadingGifDisappear() {
 document.getElementById('myLoadingGif').style.display = 'none';
}
</script>

这是我在PHP代码之前替换的HTML代码,

<img src="ajax-loader.gif" id="myLoadingGif">

有什么建议吗?

谢谢!

尝试在

while 循环中放置一个检查,这将检查(mysqli_num_rows($result)==0)这意味着如果表返回了任何数据。但是,请使用 if statement 内部循环,这样您就不会在每次循环运行时都放置加载程序。取回数据后,loop将退出,您可以继续处理数据。:D

将动画图像标记放在使用 CSS 定位的div中,以覆盖您希望覆盖的屏幕部分,并确保它是加载到页面正文中的第一件事:

<div class="animated">
    <img src="ajax-loader.gif" id="myLoadingGif">
</div>

现在,您可以在页面加载完成后隐藏动画div,方法是在结束正文标记之前添加以下内容(显示以供参考):

<script type="text/javascript">
window.onload = function() {
    document.getElementsByClassName('animated').style.display = 'none';
};
</script>
</body

所以,我为解决这个问题所做的是用<img src="ajax-loader.gif" id="myLoadingGif" style= "display: none;">隐藏 GIF

用户需要选择并发送变量以使查询运行的地方,我添加了onchange='showDiv()'

激活以下功能,

function showDiv(){
      document.getElementById('myLoadingGif').style.display = "block";
}

查询完成后运行 GIF 自动切换到display: none;这是完美的!