c# - jquery $.when 不通过母版页中的等待功能工作

标签 c# jquery asp.net .when

当我使用 jquery.when 使用母版页在 Web 表单中运行时遇到一些问题

这是我使用母版页的 Web 表单代码

$(document).ready(function(){
  $.when(masterPageFunction()).done(function(){
     webFormFunction();
  });
})

这是我的母版页

function masterPageFunction() {
   //In this function i call 2 ajax like this
    $.ajax({
         type: "POST",
         url: "/api/master/xxx/",
         data: JSON.stringify(obj),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
               $.ajax({
                        type: "POST",
                        url: "/api/master/xxx2/",
                        data: JSON.stringify(obj),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {

                        }
              })
         }
   })
}

结果是当母版页功能未完成时网络功能正在运行 请帮忙,非常感谢

最佳答案

您很接近,但是 whenthendone 函数依赖于 promise 。您不会在代码中返回任何 promise ,因此它只是直接运行。

首先,您需要在母版页的 done 函数中获取 promise 完成后的结果。为此,我们将向回调添加一个 response 参数,然后将其传递给 webFormFunction

$(document).ready(function(){
  $.when(masterPageFunction()).done(function(response){
     webFormFunction(response);
  });
})

接下来,我们需要向 masterPageFunction 添加一个 promise 并返回它。您使用要发送回母版页中的 done 函数的响应来解决 promise 。像这样:

function masterPageFunction() {

    // Create the promise
    var deferred = $.Deferred();

    //In this function i call 2 ajax like this
    $.ajax({
        type: "POST",
        url: "/api/master/xxx/",
        data: JSON.stringify(obj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $.ajax({
                type: "POST",
                url: "/api/master/xxx2/",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    // Resolve the promise with the response from $.ajax
                    deferred.resolve(response);
                }
            });
        }
    });

    // Return the promise (It hasn't been resolved yet!)
    return deferred.promise();
}       

这样,webFormFunction 将不会被调用,直到第二次 ajax 调用完成,即 resolve the promise。

关于c# - jquery $.when 不通过母版页中的等待功能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610021/

相关文章:

c# - 以编程方式创建 ListView 项的绑定(bind)

c# - 首先将外键映射到 EF 代码中的非主代理键列

c# - Visual Studio 不会在崩溃时进行调试

c# - 在 BetterCms 中批量发布页面

javascript - CSS、JS 或 JQuery 中是否有一种方法可以根据位置更改文本的颜色?

javascript - 如何选择正确的 'this' 选择器?

javascript - 在鼠标悬停时触发 'further information' div(有重叠)

c# - 在 ASP .NET 中通过 C# 获取存储过程脚本

asp.net - 如何在不使用 Visual Studio 的情况下使用 ASP.NET MVC 实现站点?

c# - 如何实现撤销功能