闭包不能返回值

cant return value out of closure

本文关键字:返回值 不能 闭包      更新时间:2023-09-26

我似乎无法让这个值将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再次为false

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;
        }
    });
}