gpt4 book ai didi

javascript - 多个 JSON 文件调用

转载 作者:行者123 更新时间:2023-12-03 06:25:18 25 4
gpt4 key购买 nike

谁能帮我解决以下问题。我有 2 个 JSON 文件:

  1. names.json:其中包含每个人的所有姓名年龄和地址数组(如果有多个居住地)。
    {
    "people":
    [
    {
    "name":"Peter Gabriel",
    "age":42,
    "address": ["location1","location2","location3"]
    },
    {
    "name":"Mark Vincent",
    "age":"25",
    "address": ["location4","location5"]
    }
    ]
    }

  2. data.json:包含所有地址详细信息
    {
    "location1":
    {
    "country":"Switzerland",
    "street":"some Avenue",
    "number": 32
    },
    "location2":
    {
    "country":"Latvia",
    "street":"some Street",
    "number": 43
    },
    "location3":
    {
    "country":"Denmark",
    "street":"some Road",
    "number": 16
    },
    "location4":
    {
    "country":"Austria",
    "street":"some Avenue",
    "number": 54
    },
    "location5":
    {
    "country":"Poland",
    "street":"some Avenue",
    "number": 23
    }
    }
    我需要将 data.json 文件数据放在全局中并在 names.json 之前加载,但由于 JSON 加载是一个异步函数,我该怎么做。

    var jsonAddressData = [];
    function main()
    {
    loadNamesJSON(function(response) {
    jsonAddressData = JSON.parse(response);
    });


    loadNamesJSON(function(response) {
    var jsonPeopleData = JSON.parse(response);
    var addressDetail=[];

    for(var i in jsonPeopleData.people){
    // ACCESS ADDRESS OBJECT DETAILS HERE
    for(var j in jsonPeopleData.people[i].address){
    if (jsonPeopleData.people[i].address[j] in jsonAddressData){

    addressDetail.append(jsonAddressData[jsonPeopleData.people[i].address[j]])
    }
    }
    }
    });
    }

    function loadNamesJSON(callback) {
    var request = new XMLHttpRequest();
    request.overrideMimeType("application/json");
    request.open('GET', 'names.json', true);

    request.onreadystatechange = function () {
    if (request.readyState === 4 && request.status ===200) {
    callback(request.responseText);
    }
    };
    request.send(null);
    }

    function loadDataJSON(callback) {
    var request = new XMLHttpRequest();
    request.overrideMimeType("application/json");
    request.open('GET', 'data.json', true);

    request.onreadystatechange = function () {
    if (request.readyState === 4 && request.status ===200) {
    callback(request.responseText);
    }
    };
    request.send(null);
    }

最佳答案

在原始 JavaScript 中你可以这样做:

function phpEncode(obj){
var r = [];
if(obj instanceof Array){
for(var i=0,l=obj.length; i<l; i++){
r.push(phpEncode(obj[i]));
}
return '%5B'+r.join(',')+'%5D';
}
else if(typeof obj === 'object' && obj){
for(var i in obj){
if(obj.hasOwnProperty(i)){
var v = obj[i], s;
if(typeof v === 'object' && v){
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":')+phpEncode(v);
}
else{
v = typeof v === 'string' ? '"'+v.replace('"', '\"')+'"' : v;
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":'+v);
}
r.push(s);
}
}
return '%7B'+r.join(',')+'%7D';
}
else{
r = typeof obj === 'string' ? '"'+obj.replace('"', '\\"')+'"' : obj;
return ''+r;
}
}
function phpDecode(url){
return eval('('+decodeURIComponent(url)+')');
}
function post(send, where, success, context){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
var c = context || this;
x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
if(success)success.call(c, phpDecode(x.responseText));
}
}
if(typeof send === 'object' && send && !(send instanceof Array)){
var r = [];
for(var p in send){
r.push(encodeURIComponent(p)+'='+phpEncode(send[p]));
}
x.send(r.join('&'));
}
else{
throw new Error('send must be an Object');
}
}
post({}, 'data.json', function(obj1){
// obj1 holds data.json Object
post({}, 'names.json', function(obj2){
// obj2 holds names.json Object
});
});

请随意更改上面的代码以满足您的需求。例如我正在使用 POST 请求。当然,这对你来说并不重要。

如果使用 jQuery:

$.getJSON('data.json', function(obj1){
// obj1 holds data.json Object
$.getJSON('names.json', function(obj2){
// obj2 holds names.json Object
});
});

需要注意的重要一点是 AJAX 是异步的,因此后面的所有代码都必须位于 success 函数内。换句话说,如果你这样做:

$.getJSON('data.json', function(obj1){
var whatever = obj1;
// obj1 holds data.json Object
$.getJSON('names.json', function(obj2){
// obj2 holds names.json Object
});
});
console.log(whatever);

console.log(whatever) 将返回 undefined,因为除非 AJAX 发生得非常快,否则它不会发生。无论如何,你需要一段时间才能完全理解这些东西。祝你好运。

关于javascript - 多个 JSON 文件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com