This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                2年前关闭。
        

    

我对此JavaScript函数有疑问。我正在尝试做的是,使用ajax调用查找特定的“材料描述”。当我尝试console.log ajax函数时,将显示数据。但是,当我设置为数组时,它不会设置数组值并被跳过。使用“异步:假”给我这个警告:


  不赞成在主线程上使用同步XMLHttpRequest,因为它会对最终用户的体验产生不利影响。


没有异步将给我不确定的结果。

$('#iBarcode').keypress(function (keyPressed) {
            if (keyPressed.which == 13) {
                var barcode = $('#iBarcode').val()
                var splitted = new Array()
                var arrayCnt = -1;
                for (var i = 0; i < barcode.length; i++) {
                    var flagStart;
                    if (barcode.charAt(i) == ')') {
                        flagStart = true
                        i += 1
                        arrayCnt += 1
                        splitted[arrayCnt] = ''
                    }
                    if (barcode.charAt(i) == ('(')) {
                        flagStart = false
                    }
                    if (flagStart == true) {
                        splitted[arrayCnt] = splitted[arrayCnt] + barcode.charAt(i)
                    }
                }
                console.log(setMatDesc(splitted[0])) //value showed here
                splitted[arrayCnt + 1] = setMatDesc(splitted[0]) //value not showed here and skipped?
                splitted[arrayCnt + 1] = currentDate

                $('#iBarcode').val('').focus
                console.log(splitted)
            }
        })

        function setMatDesc(MatID) {
            var result
            $.ajax({
                url: '@Url.Action("Get_MatDesc")',
                type: 'GET',
                async: false,
                data: { MatID: MatID },
                success: function (data) {
                    result=data
                },
                error: function (xhr) {
                    alert('error');
                }
            })

            return result
        }


感谢您的帮助,谢谢。

最佳答案

您需要提供一个回调函数,该函数将在ajax调用完成后执行,例如:

function setMatDesc(MatID, calback) {
        var result
        $.ajax({
            url: '@Url.Action("Get_MatDesc")',
            type: 'GET',
            async: false,
            data: { MatID: MatID },
            success: function (data) {
                callback(data); // note this
            },
            error: function (xhr) {
                alert('error');
            }
        });
}


在通话结束时,请执行以下操作:

setMatDesc(splitted[0],function(result) {

    splitted = result;
    splitted[arrayCnt + 1];
    splitted[arrayCnt + 1] = currentDate;

});


代码可能无法正常工作,因为我尚未测试过,但这是从执行ajax调用的函数返回数据的方式,因为ajax调用是异步执行的,并且该函数在ajax调用从服务器完成返回之前执行主体。

09-10 12:22
查看更多