函数返回未定义的数组:获取请求

时间:2019-02-28 18:39:49

标签: javascript

我有一个Servlet,它返回了一些JSONgetResponseField函数向该Servlet发送一个GET请求,并接收响应JSON,将其值添加到数组中并返回数组responseField。函数updateState接受getResponseField返回的数组,并根据其值更新文档的div:

$(document).on("click", "#start-button", function () {  
            var responseField = getResponseField();
            console.log("responseField in main: " + responseField);  
            //responseField in main: undefined
            updateState(responseField);

        });


function getResponseField()  {
    $.get("start", function (response) {   
        var responseField = new Array();
        var jsonData = JSON.parse(response);
        for (var i = 0; i < jsonData.length; i++) {
            for (var e=0; e<jsonData[i].length; e++)  {
                responseField.push(jsonData[i][e]);
            }

        }

        console.log("responseField in getResponseField: " + responseField);  
        //responseField in getResponseField: 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0...

        return responseField;
    });
}

function updateState(responseField)  {
        console.log("responseField in updateState: " + responseField);  
        //responseField in updateState: undefined

        var fieldDiv = document.getElementById("game-field");
        for (var i=0; i<fieldDiv.children.length; i++)  {
            if (responseField[i]==1)  {
                fieldDiv.children[i].style.backgroundColor="red";
            }
        }
}

问题是,尽管将reponseField内的getReponseField打印到console.log中,但在其他任何地方都未定义。

我还试图摆脱GET的要求,并且

function getResponseField()  {
    var responseField = new Array();
    responseField[0]='a';

    return responseField;
}

然后工作正常,我得到以下输出:

responseField in main: a
responseField in updateState: a

GET请求使数组出现错误的问题是什么?

0 个答案:

没有答案