首页 > 解决方案 > 在烧瓶中执行后台操作时如何显示加载消息?

问题描述

我有以下情况:

index.html 文件:

 <div class="col-xl-3 col-md-6">
   <div class="card bg-primary text-white mb-4">
     <div class="card-body">Prima alimentazione</div>
      <div class="card-footer d-flex align-items-center justify-content-between">
       <a id= 'firstAlimentazione' class="small text-white stretched-link">View Details</a>
        <div class="small text-white"><i class="fas fa-angle-right"></i></div>
         </div>
       </div>
    </div>

以下ajax函数连接到的

$(function() {
          $('a#firstAlimentazione').bind('click', function() {
            $.getJSON('/firstScript',
                function(data) {

            });
            return false;
          });
});

调用以下python代码

# background process happening without any refreshing
@app.route('/firstScript')
def firstScript():
    storage = restore_value()
    hostname = storage.get(1)
    port = storage.get(2)
    db_name = storage.get(3)
    name_tab = storage.get(4)
    directory_to_load = storage.get(5)
    directory_log = storage.get(6)
    print(os.system("python3 FirstSupply/script.py " + hostname+" "+port+" "+db_name+" "+name_tab+" "+directory_to_load+" " + directory_log))
    return "nothing"

由于“python3 脚本”可能需要几分钟才能完成,我想显示一个警报以指示操作的加载和随后的终止。

我怎样才能做到这一点?

标签: pythonajaxflaskbootstrap-4

解决方案


这是我在我的 Flask 项目中采用的一种方法。

我有一个加载器,包含在要显示此类消息的页面上。我会在模板的底部放这样的东西:

{% include "loading-modal.html" %}

内容可以是任何你想要的。它可能只是一个简单的消息/警报,也可能是某种动画。我在简单动画的底部包含了链接。

此加载器的样式将包括:

display: none;

这样加载器就不会显示给用户。然后,当我运行我的 ajax 函数时,我将使加载程序可见,如下所示:

var loader = document.getElementById('loading-bg');
loader.style.display = 'block';

这将使加载器可见,直到我再次隐藏它,或者将用户重定向到他们下一个要访问的任何页面。在后台发生的任何事情将结果返回给我的 ajax 函数之前,我不会再次隐藏模式。

这种方法假设您不需要能够向用户提供某种进度指示,或者您不能因为您不知道需要多长时间而无法提供。它还假设您的用户在此脚本运行时无法与屏幕进行交互,因为我通常会在页面内容上设置一个透明度,从而阻止所有内容。

如果您希望加载器包含某种动画,这是我以前使用过的动画:

https://tobiasahlin.com/spinkit/ https://github.com/tobiasahlin/SpinKit

我希望这有帮助。


推荐阅读