This question already has answers here:
Variable doesn't get returned from AJAX function
                                
                                    (2个答案)
                                
                        
                        
                            How do I return the response from an asynchronous call?
                                
                                    (38个答案)
                                
                        
                                6年前关闭。
            
                    
我似乎无法获得此值来将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自定义验证器。

这是正在发生的事情:


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

最佳答案

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

关于javascript - 无法传回封闭值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16733363/

10-12 18:22