我有一个Servlet
,它返回了一些JSON
。 getResponseField
函数向该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
请求使数组出现错误的问题是什么?