gpt4 book ai didi

JavaScript 与 json 数据相关的问题

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

我正在尝试获取并解析 json 数据,以便将其输出到空白 HTML 文件。我不断遇到的问题是,如果我获取数据并解析它,我会得到 Uncaught TypeError: Cannot read property 'SOCENGPRE' of undefined错误。如果我获取dataType: "text"中的json数据格式我得到 XMLHttpRequest cannot load <api url> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.错误。该网站位于本地计算机上,由于个人原因,我无法编辑服务器跨平台。代码如下所示:

var myDataVar;
function main() {
$.ajax({
url: "http://api&leagues=SOCENGPRE&format=jsonp&callback=?",
dataType: "json",
success: function (data) {
myDataVar = $.parseJSON(data);
getUpcomingFixtures();
}
});
}
function getUpcomingFixtures() {
for (var i = 0; i <= myDataVar.SOCENGPRE.fixtures.length - 1; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
console.log(myDataVar.SOCENGPRE.fixtures[i].home_team + " vs " + myDataVar.SOCENGPRE.fixtures[i].away_team);
}
}

正在获取的数据的示例如下所示:

{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}

我的目标是获取赛程 ID 和两支参赛球队。知道我做错了什么吗?

最佳答案

尝试使用下面的代码,不要再次解析 JSON,因为它已经被处理,假设 string 是您的 JSON 对象。

在脚本开头声明此变量结果为数组;

var result = [];


function getUpcomingFixtures() {
$.each( string , function ( i , val) {

$.each( val['fixtures'] , function ( k , fixturesData) {

result.push( { id: fixturesData.id ,
hometeam : fixturesData.home_team ,
awayteam : fixturesData.away_team
}
);
});

});
}

关于JavaScript 与 json 数据相关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420829/

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