【问题标题】:Rolling ball when page loads for HTML in flask在烧瓶中为 HTML 加载页面时滚动球
【发布时间】:2020-04-02 07:22:54
【问题描述】:

我是 Flask 的新手,但我试图在页面加载时显示“滚动球”。

此链接:Display a ‘loading’ message while a time consuming function is executed in Flask 很有帮助,但没有给我想要的结果。

from flask import Flask
from flask import request
from flask import render_template
import time

app = Flask(__name__)

def long_load(typeback):
    time.sleep(5) #just simulating the waiting period
    return "You typed: %s" % typeback

@app.route('/', methods=("POST", "GET"))
def test():
    if request.method == 'GET':

        return render_template('index.html')


    elif request.method == 'POST':

        query = request.form['anything']
        outcome = long_load(query)

        return render_template("post_template.html" , display=outcome)

if __name__ == '__main__':
    app.run()

index.html 节选:

<head>
<style>
div#loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite ;
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<script type="text/javascript">// <![CDATA[

        document.onreadystatechange = function() { 
    if (document.readyState !== "complete") { 
        document.querySelector("body").style.visibility = "hidden"; 
        document.querySelector("#loader").style.visibility = "visible"; 
    } else { 
        document.querySelector("#loader").style.display = "none"; 
        document.querySelector("body").style.visibility = "visible"; 
    } 
}; 

// ]]></script>


</head>

 <form action="." method="post">>  
       <body>
          <div class="caption">
              <table class="center">
                  <tr>
                    <td class="NEONpinktxt"> </td> 
                    <td align = "center"> <input type="submit" name="anything_submit" href="#" value="Search Results" id="loader" > </td>
                  </tr>
                     <div id="loader"></div>
               </table>
            </div>         
         </body>  
 </form>

当页面加载或刷新时,滚动球会显示,但是当点击“搜索结果”时,什么也没有发生。

【问题讨论】:

  • 输入没有href。您需要链接或表单
  • 为什么脚本要包裹在样式标签中?
  • @mplungjan,写这篇文章的时候搞错了,脚本不在样式标签中,现在编辑。
  • 表单也包裹了body标签。
  • 您也将页面提交到服务器。为什么悸动者(也就是所谓的)会跑?如果你想搜索显示一个 throbber,你需要 Ajax

标签: html python-3.x flask


【解决方案1】:

假设您可以让您的服务器返回正确的文档片段

我会改变

query = request.form['anything']

query = request.form['search']

然后执行此操作(请注意,我也修复了无效的 HTML)

document.onreadystatechange = function() {
  var complete = document.readyState === "complete";
  document.querySelector("body").style.visibility = complete ? "visible" : "hidden";
  document.getElementById("loader").style.display = complete ? "none" : "block";
}
document.getElementById("myForm").addEventListener("submit", function(e) {
  document.getElementById("result").style.display = "none";
  document.getElementById("loader").style.display = "block";

  e.preventDefault(); // stop submit
  let token = new FormData();
  token.append('search', document.getElementById('search').value);
  fetch(this.action, {      // form action 
      method: this.method,  // form method
      body: token
    })
    .then(response => response.text())
    .then(fromServer => {
      document.getElementById('result').innerHTML = fromServer;
      document.getElementById("result").style.display = "block";
      document.getElementById("loader").style.display = "none";

    });
})
div#loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  /* Safari */
  animation: spin 2s linear infinite;
}


/* Safari */

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
<form id="myForm" action="getInformattionFromServer" method="post">
  <div class="caption">
    <table class="center">
      <tr>
        <td class="NEONpinktxt"><input type="text" id="search" value="" placeholder="Search something" /> </td>
        <td align="center"> <input type="submit" value="Search Results"> </td>
      </tr>
    </table>
    <div id="loader"></div>
    <div id="result"></div>
  </div>
</form>

【讨论】:

  • div(加载器和结果)在当前位置无效
【解决方案2】:

作为使用loading circle 处理长时间运行的任务的演示,我拼凑了一个简单的演示,它使用 Ajax 向某个服务器发送请求 - 颤动器在请求开始时被激活并一直运行到长时间运行的任务完成并收到回复。

loader 被分配了 throbber 类,因此它会在页面加载时播放 - 尽管它非常快,您在这里几乎没有注意到。

稍微修改了css,以便可以单独应用动画。

原始 HTML 无效,因此已更正。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        /* emulate long running tasks as result of XHR query */
        sleep(mt_rand(2,5));

        /* mickey mouse data for demo only */
        $_POST['time']=time();
        $_POST['ip']=$_SERVER['REMOTE_ADDR'];
        $_POST['date']=date(DATE_ATOM);
        exit(json_encode($_POST));
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>ball loader</title>
        <style>

            body{visibility:hidden;}

            div#loader {
                display:inline-block;   /* occupies less vertical space! */
                width: 120px;
                height: 120px;
            }

            .throbber{
                border: 16px solid #f3f3f3;
                border-radius: 50%;
                border-top: 16px solid #3498db;
                visibility:visible;

                -webkit-animation: spin 2s linear infinite; /* Safari */
                animation: spin 2s linear infinite ;            
            }

            @-webkit-keyframes spin {
                0% { -webkit-transform: rotate(0deg); }
                100% { -webkit-transform: rotate(360deg); }
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

        </style>
        <script>

            const ajax=function(url,params,callback){
                let xhr=new XMLHttpRequest();
                xhr.onload=function(){
                    if( this.status==200 && this.readyState==4 )callback( this.response )
                };
                xhr.onerror=function(e){
                    alert(e)
                };
                xhr.open( 'POST', url, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
                xhr.send( params );
            };


            document.addEventListener('DOMContentLoaded',function( event ){
                const submit=document.forms.search.querySelector('input[type="submit"]');
                const input=document.forms.search.querySelector('input[ type="text" ][ name="anything" ]');
                const throbber=document.getElementById('loader');
                const out=document.querySelector('output');

                document.body.style.visibility='visible';
                throbber.classList.remove('throbber');




                submit.addEventListener('click',function(e){
                    e.preventDefault();
                    throbber.classList.add('throbber');

                    ajax( location.href, 'anything='+input.value, function(r){
                        throbber.classList.remove('throbber');
                        out.textContent=r
                    })
                });
            });
        </script>
    </head>
    <body>
        <form name='search' method='post'>
            <div class='caption'>
                <table class='center'>
                    <tr>
                        <td class='NEONpinktxt'>
                            <input type='text' name='anything' value='banana' />
                        </td> 
                        <td align='center'>
                            <input type='submit' name='anything_submit' value='Search Results' />
                        </td>
                    </tr>
                </table>

                <div id='loader' class='throbber'></div>
            </div>
        </form>
        <output></output>
    </body> 
</html>

【讨论】:

  • 在输入类型为“数字”的情况下,即&lt;td class='NEONpinktxt'&gt; &lt;input type='number' name='anything' value='banana' /&gt; &lt;/td&gt;。您的脚本仍然有效吗?
  • 香蕉不是数字...如果您使用数字而不是香蕉,脚本应该可以正常工作 - 这只是为了说明如何设置类来为微调器设置动画并删除一次 @987654326 @已完成
  • 哦,好的,但是当我按照您的建议进行操作时,结果不会像我的原始脚本那样显示在新页面上,而是仅显示在搜索页面上......只是故障排除知道可能是什么问题。
  • 好的 - 我想,读了几次我明白你的意思,但我不确定你以前如何让结果出现在不同的页面上。表单操作设置为.,我认为这是同一页(从未使用. 进行表单操作,我也没有看到它使用过)所以结果应该在同一页上?如果您打算显示微调器,而一些复杂的任务是由服务器计算的,那么传统的表单提交并不能真正起作用,因此使用 ajax
猜你喜欢
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
相关资源
最近更新 更多