【问题标题】:jquery $.when not working by waiting function in master pagejquery $.when 不通过母版页中的等待功能工作
【发布时间】:2018-11-09 14:58:35
【问题描述】:

当我使用 jquery.when 使用母版页在 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) {

                        }
              })
         }
   })
}

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

【问题讨论】:

  • 为什么你对两个单独的 Ajax 调用使用相同的参数,但对任何一个的响应都不做任何事情?为什么不把它们分开呢?因为它已经异步执行了?
  • 这只是一个例子。
  • 我们需要更多信息,这个例子没有提供足够的细节。
  • 我也相信你想返回一个承诺,但你的代码结构方式不会按照预期的方式工作。你可能把异步函数和 promise 混在一起了。

标签: c# jquery asp.net .when


【解决方案1】:

您已经接近了,但 whenthendone 函数依赖于 Promise。您没有在代码中返回任何承诺,因此它只是直接运行。

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

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

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

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 调用完成之前不会被调用,这将解决 promise。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多