jQuery返回值未定义

Bob*_*nes 6 jquery

固定!谢谢!请参阅下面的"更正代码".

目标是从对话框中获取数据.我看过很多文章,但是无法使用它们,所以我决定使用Web服务在对话框和底层页面之间来回传递数据.

除了读取从Web服务返回的值的代码之外,所有代码都已到位.我可以在调试器中看到数据正在被传回,但是当我返回调用者时,返回的数据是未定义的.

jQuery函数getLocal调用AJAX,返回好的数据,但是当它返回到调用它的函数(verbListShow)时,返回的值是"未定义的".

这一切都发生在一个主要用jQuery编写的ASP.NET页面中,并打开一个jQuery对话框.

function getLocal(name) {
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            var rtn = data.d;
            return rtn;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

上面的代码可以工作,但是在调用时,rtn是未定义的.这是来电者:

function verbListShow(dutyNumber) {

    $('#dlgDutyList').dialog({
        modal: true,
        show: "slide",
        width: 250,
        height: 250,
        open: function (event, ui) {
            setLocal("DUTYNUMBER", dutyNumber);
        },
        buttons: {
            "Select": function () {
                var id = getLocal("VERBID"); // <*** Returns undefined
                var verb = getLocal("VERB"); // <*** Returns undefined
                $.ajax({
                    type: "POST",
                    async: false,
                    url: "WebServices/FLSAService.asmx/SetDuty",
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: verb }),
                    success: function (data) {
                        data = $.parseJSON(data.d);
                        if (data.ErrorFound) {
                            showMessage(data.ErrorMessage, 2, true);
                        }
                        else {
                            log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("updateDuty: "
                            + XMLHttpRequest.responseText);
                    }
                });

                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }

    });
    $('#dlgDutyList').dialog('open');
Run Code Online (Sandbox Code Playgroud)

固定代码:

function getLocal(name) {
var rtn = "";
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            rtn = data.d;
        }
    });
return rtn;
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*oli 9

它违背了AJAX同步使用它的目的(AJAX代表Asynchronous Javascript和Xml).

现在,您不能return使用success方法中的值,但可以将其存储在变量中,然后返回该值

function getLocal(name) {
    var returnValue;
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            returnValue = data.d;
        }
    });
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

但正确的方法是使用延迟对象

function getLocal(name, resultset) {
    return $.ajax({
        type: "POST",
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            resultset[name] = data.d;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

并称之为

"Select": function() {
    var results = {};
    var self = this;
    $.when(getLocal("VERBID", results), getLocal("VERB", results)).then(function(){
        $.ajax({
            type: "POST",
            url: "WebServices/FLSAService.asmx/SetDuty",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                dutyNum: dutyNumber,
                id: results.VERBID,
                verb: results.VERB
            }),
            success: function(data) {
                data = $.parseJSON(data.d);
                if (data.ErrorFound) {
                    showMessage(data.ErrorMessage, 2, true);
                }
                else {
                    log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("updateDuty: " + XMLHttpRequest.responseText);
            }
        });
    }).always(function(){
        $(self).dialog("close");
    });
}
Run Code Online (Sandbox Code Playgroud)


Woj*_*acz 5

一切都是因为$ .ajax函数由于其异步行为而不会返回任何值,我的建议是为getLocal称为“回调”的方法设置第二个参数。

正确的方法是这样做:

function getLocal(name, callback) {
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            var rtn = data.d;
            callback(rtn);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

然后,您的主代码必须看起来像这样(异步代码):

//some code here
buttons: {
            "Select": function () {
                getLocal("VERBID", function(id) {
                     getLocal("VERB", function(verb) { 
                        $.ajax({
                           type: "POST",
                           async: false,
                           url: "WebServices/FLSAService.asmx/SetDuty",
                           dataType: 'json',
                        //some code here
                     });
                });
//some code here
Run Code Online (Sandbox Code Playgroud)

为了改进此代码,一次要进行两个异步调用,可以使用jQuery Deferred对象,并.resolve(data)在所有ajax调用获得正确响应后立即对其运行。