使用JS

时间:2016-03-14 14:19:18

标签: javascript variables text set

在我的程序中我有一个变量

untangleGame.levels = 
[
 {
 "level" : 0,

 "circles" : [{"x" : 400, "y" : 156},
 {"x" : 381, "y" : 241},
 {"x" : 84, "y" : 233},
 {"x" : 88, "y" : 73}],

 "relationship" : {
 "0" : {"connectedPoints" : [1,2]},
 "1" : {"connectedPoints" : [0,3]},
 "2" : {"connectedPoints" : [0,3]},
 "3" : {"connectedPoints" : [1,2]}
 }
 },////////****** More Levels****///////


]

我必须将此变量存储在文本文件中。我创建了一个函数

function loadDoc() {
var client = new XMLHttpRequest();
client.open('GET', '/KB/canvasAts/levels.txt');
client.onreadystatechange = function() {
if (client.readyState == 4 && client.status == 200) 
{
   untangleGame.levels = JSON. parse (client.responseText) ;
}
}
client.send();
}

警报功能显示文本,但变量仍未设置,我收到错误消息"未捕获TypeError:无法读取属性' 0'未定义"在var level = untangleGame.levels[untangleGame.currentLevel];

2 个答案:

答案 0 :(得分:0)

您需要将文本解析为JSON。

替换此行

untangleGame.levels = client.responseText;

untangleGame.levels = JSON.parse(client.responseText);

您需要保留早期if condition

if (client.readyState == 4 && client.status == 200) 
{
  alert(client.responseText);
  untangleGame.levels = JSON. parse (client.responseText) ;
}

您收到错误

Uncaught TypeError: Cannot read property '0' of undefined

因为如果你在if.条件之外这样做,那么你的值可能还没有填充,因为当时client.responseText可能是空的。

答案 1 :(得分:0)

试试这个:

loadDoc('/KB/canvasAts/levels.txt', function (response) {
    untangleGame.levels = JSON.parse(response) ;

});

function loadDoc(fileName, callback) {

var client = new XMLHttpRequest();
client.overrideMimeType("application/json");
client.open('GET', fileName, true);
client.onreadystatechange = function () {
    if (client.readyState == 4 && client.status == "200") {
        callback(client.responseText);
    }
};
  client.send(null);
}