简体   繁体   English

使用JavaScript数组从JSON文件请求数据

[英]Using a javascript array to request data from a JSON file

I was wondering if it's possible to request data from a JSON file (For example: customers.name). 我想知道是否可以从JSON文件中请求数据(例如:customers.name)。 But instead of that using an array containing the JSON object names and looping it. 但是,而不是使用包含JSON对象名称的数组并对其进行循环。 My code is below. 我的代码如下。

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

load("klanten.json", function(response) {
    var klanten = JSON.parse(response);
    //Array containing JSON file object names.
    var infArray = ['name', "address", "email", "phone", "place", "zip"];
    //Calling said info using a for loop.
    for(var i = 0; i < infArray.length; i++) {
      console.log(klanten[i].infArray[i]);
      //It not working for some reason.
    }
});

I`d love some help with this. 我很乐意为此提供帮助。 And in case what im asking is completely stupid, also let me know! 万一我问的是完全愚蠢的,也让我知道! Any help is welcome, thanks! 欢迎任何帮助,谢谢!

Change console.log(klanten[i].infArray[i]); 更改console.log(klanten [i] .infArray [i]); to: 至:

console.log(klanten[i][infArray[i]]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM