简体   繁体   English

等待AJAX​​通话时显示一次加载图标

[英]Display loading icon once while waiting for AJAX call

I'm populating a table with data that automatically updates every 4 seconds using AJAX. 我正在用数据填充表格,该数据使用AJAX每4秒自动更新一次。 I want to display a loading message while waiting for the AJAX to load on the initial page load only. 我想在等待AJAX​​仅在初始页面加载时显示加载消息。

At the moment I have managed to display the loading message but the message appears every time the data is updated via AJAX (Every 4 seconds) - I want the loading message to only display on the initial page load before the AJAX loads initially. 目前,我已设法显示加载消息,但是每次通过AJAX更新数据时都会显示该消息(每4秒)-我希望加载消息仅在初始加载AJAX之前显示在初始页面加载上。 All subsequent AJAX updates should not display the loading message as the table has already been populated with data. 所有后续的AJAX更新都不应显示加载消息,因为该表已经填充了数据。

<div id="loading" style="display: none;">Loading..</div>

<script type="text/javascript">
    $(document).ajaxStart(function(){
        $("#loading").show();
        }).ajaxStop(function() {
        $("#loading").hide();
    });
</script>
<script type="text/javascript">
    var auto_refresh = setInterval(
    function () {
        $('#load_onlineusers').load('/online_players.php').fadeIn("slow");
    }, 4000); 
</script>
<div id="load_onlineusers"> </div>

Above is the code that is causing the loading message to display every 4 seconds. 上面是导致加载消息每4秒显示一次的代码。

Use beforeSend method to show loading message and control using a global variable: 使用beforeSend方法显示加载消息并使用全局变量进行控制:

var executed = false;
$.ajax({ url: "", 
    type: "", 
    data: "", 
    beforeSend: function() {
        if (!executed) {
            // Show loading
            executed = true;
        }
    },
    complete: function() {
        // Hide loading
    },
    success: function(data) {

    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM