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

时间:2016-02-10 17:50:40

标签: javascript php jquery ajax

我有一个带加载动画的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">

有什么建议吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

将动画图片标记放置在使用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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

隐藏GIF

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

激活下面的功能,

function showDiv(){

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

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