如何在jQuery中创建一个加载轮,当Python中的后台进程完成时,它会隐藏自己?

dauxcl2d  于 2023-06-29  发布在  jQuery
关注(0)|答案(2)|浏览(96)

我正试图使加载轮显示,而后台进程正在运行,并隐藏自己的后台进程完成。后台进程是摄取进程,它在Wikipedia页面上运行web scraper并将其转换为文本文件,然后将其摄取到LLM模型中。我希望加载gif在整个摄取运行期间出现,然后在完成时消失。我使用Flask在前端和后端之间进行通信。
我在POST请求上尝试了ajaxComplete,它只显示了一毫秒的轮子,以及在我下面的代码中发布的当前方法。
联系我们

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style> #loading { display: none; } </style>
<div class="card-footer">
            <form id="ingestArea" class="input-group">
                <input type="text" id="html" name="url" placeholder="Type your message..." autocomplete="off" class="form-control type_msg" required/>
                <div class="input-group-append">
                    <button type="submit" id="feed" class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></button>
                </div>
                <div id="loading"><img src="https://i.pinimg.com/originals/36/3c/2e/363c2ec45f7668e82807a0c053d1e1d0.gif"></div>
            </form>
        </div>
<script>
            $(document).ready(function() {
                var interval;
                $("#messageArea").on("submit", function(event) {
                    const date = new Date();
                    const hour = date.getHours();
                    const minute = date.getMinutes();
                    const str_time = hour+":"+minute;
                    var rawText = $("#text").val();

                    var userHtml = '<div class="d-flex justify-content-end mb-4"><div class="msg_cotainer_send">' + rawText + '<span class="msg_time_send">'+ str_time + '</span></div><div class="img_cont_msg"><img src="https://i.ibb.co/d5b84Xw/Untitled-design.png" class="rounded-circle user_img_msg"></div></div>';
                    
                    $("#text").val("");
                    $("#messageFormeight").append(userHtml);

                    $.ajax({
                        data: {
                            msg: rawText,   
                        },
                        type: "POST",
                        url: "/get",
                    }).done(function(data) {
                        var botHtml = '<div class="d-flex justify-content-start mb-4"><div class="img_cont_msg"><img src="https://i.ibb.co/fSNP7Rz/icons8-chatgpt-512.png" class="rounded-circle user_img_msg"></div><div class="msg_cotainer">' + data + '<span class="msg_time">' + str_time + '</span></div></div>';
                        $("#messageFormeight").append($.parseHTML(botHtml));
                    });
                    event.preventDefault();
                });
                $("#ingestArea").on("submit",function(event) {
                    var rawText = $("#html").val();
                    $('#loading').show();
                    interval = setInterval(checkStatus, 1000);
                    $("#html").val("");
                    $.ajax({
                        data:{
                            url: rawText,
                        },
                        type: "POST",
                        url: "/ingest",
                    });
                });
            });
            function checkStatus() {
                $.ajax({
                    url: '/check_status',
                    type: 'GET',
                    success: function(response) {
                        if (response.status === "in_progress") {
                            $('#loading').show();
                        } else{
                            clearInterval(interval);
                            $('#loading').hide();
                        }
                    },
                    error: function(xhr) {
                        clearInterval(interval);
                        $('#loading').hide();
                    }
                });
        </script>

python(使用Flask):

is_ingesting = False

@app.route('/check_status', methods=['GET'])
def check_status():
    global is_ingesting
    if is_ingesting:
        return jsonify(status="in_progress")
    else:
        return jsonify(status="completed")

def ingest():
    global is_ingesting
    is_ingesting = True
    start_url = request.form["url"]
    scrape_web(start_url, 0)
    if does_vectorstore_exist(persist_directory):
        # Update and store locally vectorstore
        print(f"Appending to existing vectorstore at {persist_directory}")
        db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
        collection = db.get()
        texts = process_documents([metadata['source'] for metadata in collection['metadatas']])
        print(f"Creating embeddings. May take some minutes...")
        db.add_documents(texts)
    else:
        # Create and store locally vectorstore
        print("Creating new vectorstore")
        texts = process_documents()
        print(f"Creating embeddings. May take some minutes...")
        db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory,
                                   client_settings=CHROMA_SETTINGS)
    db.persist()
    db = None
    is_ingesting = False
    print(f"Ingestion complete! You can now run privateGPT.py to query your documents")
    return jsonify("All done!")
i7uq4tfw

i7uq4tfw1#

这个问题似乎是重新加载的提交按钮,这是在一个形式,使元素得到显示和即时隐藏的css上重新加载。
也许可以使用jquery click事件来避免在单击时重新加载页面。

ozxc1zmp

ozxc1zmp2#

上面的评论是正确的!这是一个刷新问题。我还学习了preventDefault()方法!这似乎是一个同样正确的解决方案。下面是编辑后的代码,用于与我以前的代码进行比较!

$("#ingestArea").on("submit",function(event) {
                    event.preventDefault();
                    var rawText = $("#html").val();
                    $("#html").val("");
                    $.ajax({
                        data:{
                            url: rawText,
                        },
                        type: "POST",
                        url: "/ingest",
                        beforeSend: function() {
                            $('#loading').show();
                        },
                        complete: function(data) {
                            $('#loading').hide();
                        },
                    });

下面是编辑后的jQuery。我把样式隐藏在顶部。这似乎工作得很好!我删除了跟踪进度的函数的不必要的python代码。

相关问题