如何在加载时延迟AJAX并显示进度条



我在侧边栏中有复选框,当用户从侧边栏中选择复选框时,它正常显示帖子。

在显示Ajax结果之前,需要使用进度栏延迟?

我的ajax代码:

<script>
jQuery(document).ready(function($){
   $('#test .br').click(function(){
    // declaring an array
    var choices = {};
    $('.contents').remove();
    $('.filter-output').empty()
    $('input[type=checkbox]:checked').each(function() {
        if (!choices.hasOwnProperty(this.name))
            choices[this.name] = [this.value];
        else
            choices[this.name].push(this.value);
    });

    console.log(choices);
    $.ajax({
        url: ajaxobject.ajaxurl,
        type :'POST',
        data : {
            'action' : 'call_post',
            'choices' : choices,
        },
        success: function (result) {
            $('.filter-output').append(result);
        }     
    });
  })
});
</script>

使用Ajax开始/停止处理程序:

var loading = $('.loader').hide();
$(document)
  .ajaxStart(function() {
    loading.show();
  })
  .ajaxStop(function() {
    loading.hide();
  });

html:

 <div class="loader" style="display:none;"></div>

CSS:

.loader {
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

在超时函数中调用您的功能,将您理想的延迟时间放置。

setTimeout(function() {
   call your function here.
 }, 10);

使用 window.setTimeout()在延迟上执行ajax。

编辑:如果您不想延迟Ajax调用并延迟响应,则将超时放在成功处理程序中:

<script>
jQuery(document).ready(function($){
   $('#test .br').click(function(){
    // declaring an array
    var choices = {};
    $('.contents').remove();
    $('.filter-output').empty()
    $('input[type=checkbox]:checked').each(function() {
        if (!choices.hasOwnProperty(this.name))
            choices[this.name] = [this.value];
        else
            choices[this.name].push(this.value);
    });
    // show the progress bar
    $('.progress-bar').show();    
    console.log(choices);
    $.ajax({
        url: ajaxobject.ajaxurl,
        type :'POST',
        data : {
            'action' : 'call_post',
            'choices' : choices,
        },
        success: function (result) {
            window.setTimeout(function() {
                // hide the progress bar
                $('.progress-bar').hide();
                $('.filter-output').append(result);
            }, 2000);   // Delay displaying the result by 2 seconds
        }
    });
  })
});
</script>

最新更新