【问题标题】:How to have JQuery wait to complete a section of code before moving on with MVC Core如何让 JQuery 在继续使用 MVC Core 之前等待完成一段代码
【发布时间】:2021-02-16 19:59:16
【问题描述】:

我希望用户按下下载按钮。该按钮将调用一个 JQuery 函数,该函数将启动加载模式,运行 Url.Action 请求,然后在操作完成运行后立即停止模式。不幸的是,JS 启动然后停止我的模态,即使它还没有完成运行我的 Url.Action

代码:

$('#DownloadBtn').click(function () {
    var modal = document.getElementById("myModal");
    modal.style.display = "block"; // starts the loading modal display when button is pressed

    location.href = '@Url.Action("Download", "Home")'; //action to download begins (this usually takes around 10 seconds to run through, that's why I want that modal running until the action is finished)

    modal.style.display = "none"; //this switches to none before the above Action has even completed
}

【问题讨论】:

  • 设置location.href 将导致当前页面被卸载,因此在此之后您无法对DOM 进行任何更改。无论如何都需要隐藏模式似乎几乎完全是多余的,因为传输页面的操作无论如何都会导致内容更新。

标签: javascript jquery asp.net-core-mvc modal-dialog


【解决方案1】:

您可以像这样使用 setTimeout 来延迟模式关闭

$('#DownloadBtn').click(function () {
    var modal = document.getElementById("myModal");
    modal.style.display = "block";
    location.href = '@Url.Action("Download", "Home")';
    
    setTimeout(() => {
        modal.style.display = "none"
    }, 10000); // Delay in ms
}

等待@Url.Action 完成将是理想的解决方案,但我什至找不到任何相关信息。

【讨论】:

    【解决方案2】:

    您可以使用 AJAX(异步 JavaScript 和 XML)

    我建议你读一读

    https://www.w3schools.com/js/js_ajax_intro.asp

    然后带着问题回来。

    有很多方法可以使用 AJAX。您可以忽略不需要的 XML 部分。

    w3schools 文章说明了在没有框架的情况下使用 AJAX,即 vanilla javascript。但是您可以使用 JQuery (https://api.jquery.com/jquery.ajax/) 和其他框架来实现相同的目标,而无需了解细节,尽管仍有学习曲线。我不为此使用框架,vanilla JS 完美且占用空间小。

    我会发布代码,但我不断收到格式错误,抱歉。

    【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2020-02-24
    • 2021-12-29
    相关资源
    最近更新 更多