gpt4 book ai didi

javascript - AJAX:如何读取 JSON 数据

转载 作者:行者123 更新时间:2023-11-28 17:31:30 24 4
gpt4 key购买 nike

我正在尝试从 url 获取 json 数据。这是js

var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'URL that has JSON format');
myRequest.onload = function() {
var myData = JSON.parse(myRequest.responseText);
console.log(myData);
};
myRequest.send();

JSON数据格式是这样的

"ING":
[
{
"#":1,
"Team":"Manchester City",
"Main":37,
"Poin":97
},
{
"#":2,
"Team":"Manchester United",
"Main":37,
"Poin":78
},
{
"#":3,
"Team":"Tottenham Hotspur",
"Main":37,
"Poin":74
},
{
"#":4,
"Team":"Liverpool",
"Main":37,
"Poin":72
},
{
"#":5,
"Team":"Chelsea",
"Main":37,
"Poin":70
}
]
}

例如我想获取 Chealsea。我怎样才能做到这一点?我知道我必须改变

console.log(myData);

我该怎么办?谢谢

最佳答案

您可以使用回调、promise 或 async/await。您可以通过以下方式使用回调来获取和使用检索到的数据:

function getUrl(url, callback) {
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url);
myRequest.onload = function() {
var myData = JSON.parse(myRequest.responseText);
console.log(myData);
callback(myData);
};
myRequest.send();
}

您请求并使用您的数据,如下所示:

getUrl('URL for JSON DATA', function(data) {
// find chealsea
var chealsea = data.ING.find(function(entry) { return entry.Team === 'Chealsea' });
console.log(chealsea);
});

关于javascript - AJAX:如何读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297524/

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