将值分配给回调函数中的变量

问题描述 投票:-2回答:1

因此,我有一个名为'levels'的变量,我使用AJAX从Web服务器上获取了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
        }        
    }
)
javascript php ajax function callback
1个回答
-1
投票

您的示例无效,因为您尝试像Chris G所说的未声明的变量那样阅读。您要查找的变量是回调的data参数

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

您绝对应该看一下jonrsharpe在他的评论中链接的内容。

也请考虑fill(),因为它更合适

© www.soinside.com 2019 - 2024. All rights reserved.