为回调函数中的变量分配值

时间:2019-12-28 11:14:38

标签: javascript php ajax function callback

所以我有一个名为'levels'的变量,我使用AJAX从网络服务器获取我的levels.json。现在,我需要获取矩阵并将它们放入级别数组。一切工作都很好,直到我想达到可以推入任何数据的水平为止,我尝试了一些示例,但没有用。有任何想法如何为级别分配价值吗?

JSON如下所示:

{   
    "easy" : [
        [1, 2, 3, 0, 0],
        [0, 0, 0, 4, 0],
        [0, 4, 2, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 1, 3, 0]
    ],
    "medium" : [
        [2, 0, 0, 9, 0, 0, 0, 5, 0],
        [1, 0, 0, 8, 0, 11, 0, 0, 5],
        [0, 2, 0, 0, 6, 0, 7, 0, 0],
        [0, 0, 0, 0, 0, 11, 0, 10, 0],
        [0, 0, 0, 7, 0, 0, 0, 0, 0],
        [0, 0, 0, 4, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 3, 6],
        [0, 9, 0, 4, 8, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 0, 10, 3]
    ],
    "hard" : [
        [1, 0, 0, 0, 3, 0, 5, 0, 2],
        [0, 0, 0, 0, 0, 0, 8, 5, 0],
        [7, 4, 0, 6, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 2],
        [0, 0, 4, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 3, 6],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 6, 0, 0, 0, 0, 8]
    ]
}

任何可悲的尝试都是这样的:

function ajax_get(url, callback)  {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            try {
                var data = JSON.parse(xmlhttp.responseText);
            } catch(err) {
                return;
            }
            callback(data);
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

ajax_get('./levels.json', function (data) {
        for (const k in data) {
            levels.push('2') // this is where i tried to push in any data and not worked
        }        
    }
)

0 个答案:

没有答案