【问题标题】:cant return value out of closure [duplicate]无法返回关闭值[重复]
【发布时间】:2013-05-24 19:00:20
【问题描述】:

我似乎无法在下面的 sn-p 中将 isValid 值从 ajax 调用中传回:

    function isShortUrlAvailable(sender, args) {
        var isValid = false;
        $.ajax({
            type: "POST",
            url: "/App_Services/ShortUrlService.asmx/IsUrlAvailable",
            data: "{url: '" + args.Value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                isValid = response.d;
            },
            error: function (msg) {
                isValid = false;
            }
        });

        args.IsValid = isValid;
    }

我确信它只是与我忽略的闭包有关。有人可以帮忙吗?

它用于 asp.net 自定义验证器。

这是正在发生的事情:

  1. isValid 在第一行设置为 false
  2. .ajax() 请求正确触发,如果其有效返回 true
  3. isValid 正确设置为 true (response.d)
  4. 当它返回到最后一行时,它认为 isValid 再次为假

【问题讨论】:

  • 简短回答你不能返回值,因为ajax是异步的,你需要使用回调来解决这个问题
  • 你不能:只有在外部函数返回后才会执行你的回调。
  • 能分享一下这个方法是怎么用的吗?
  • 我正在尝试在 <asp:CustomValidator> 中使用它,但您通过设置 args.IsValid 将值传递回 customvalidator,但它没有得到它。
  • 我似乎已经用 async: false 解决了这个问题,但我读过这在 jQuery 的未来版本和“a-bad-idea”中已被弃用

标签: javascript jquery


【解决方案1】:

AJAX 方法是异步,这意味着您的值设置为false,AJAX 调用开始,但在发生时调用args.IsValid 行。只需删除变量并在每个场景中设置args.IsValid 值:

function isShortUrlAvailable(sender, args) {
    $.ajax({
        type: "POST",
        url: "/App_Services/ShortUrlService.asmx/IsUrlAvailable",
        data: "{url: '" + args.Value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            args.IsValid = response.d;
        },
        error: function (msg) {
            args.IsValid = false;
        }
    });
}

【讨论】:

  • 谢谢,但这并没有解决问题。我以这种方式设置了一段时间,但它仍然没有将它传递回链条。我只是在阅读另一个我认为可能是解决方案的示例时才将其更改为发布的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 2014-07-15
  • 1970-01-01
相关资源
最近更新 更多