无法从关闭中返回值

时间:2013-05-24 10:55:24

标签: javascript jquery

我似乎无法获取此值以将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再次为假

1 个答案:

答案 0 :(得分: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;
        }
    });
}