json数据的JavaScript问题[重复]
Posted
技术标签:
【中文标题】json数据的JavaScript问题[重复]【英文标题】:JavaScript issues with json data [duplicate] 【发布时间】:2014-06-18 16:57:16 【问题描述】:我正在尝试获取和解析 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 和两支参赛队伍。任何线索我做错了什么?
【问题讨论】:
另外,你不应该在文本上调用$.parseJSON
,它已经被jQuery调用了,如果你再次尝试解析它会导致错误。
【参考方案1】:
尝试使用下面的代码,不要再次解析 JSON,因为它已经被处理,假设字符串是你的 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
);
);
);
【讨论】:
以上是关于json数据的JavaScript问题[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何仅使用 JavaScript 正确读取 json 文件 [重复]
JavaScript之form表单的序列化和json化[form.js]
使用 Jinja 将数据作为 JSON 对象从 Python 发送到 Javascript [重复]
访问 JSON 数组中的对象 (JavaScript) [重复]