我处于类似的位置 - 非 javascript 专家正在从事一个有趣的项目以熟悉 javascript、ajax 和 json。
我采取了三个不同的步骤来处理这个问题。我欢迎任何有关改进解决方案的反馈。
第一步是查询nfl站点以下拉分数。由于 json 的来源(即 nfl 站点)与您的站点不同,因此您必须解决针对跨域查询的 javascript 安全约束。我发现这个stackoverflow link 是一个很好的参考。我使用 JSONP 作为解决方法。我使用http://whateverorigin.org/ 作为间接站点。
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json') + '&callback=?', handleQueryForScoresResult);
正如其他人指出的那样,nfl 站点返回无效的 json 数据。以下示例行说明了该问题:
["Sun","4:25","Final",,"TEN","7","MIN","30",,,"55571",,"REG5","2012"] ,
注意空数组元素值(中间没有数据的重复逗号)。所以在我的 json 回调函数中,我通过在调用 jquery 解析 json 数据之前将空字符串(两个双引号)添加到重复的逗号来更正数据:
function handleQueryForScoresResult(data) {
var jsonStr = data.contents;
jsonStr = jsonStr.replace(/,,/g, ',"",');
jsonStr = jsonStr.replace(/,,/g, ',"",');
var scoresData = jQuery.parseJSON(jsonStr).ss;
.
.
.
}
最后,我创建了 GameScores 对象来封装 json 数据。
function GameScore(scoreData) {
this.scoreData = scoreData;
scoreData[2] = scoreData[2].toLowerCase();
scoreData[5] = parseInt(scoreData[5]);
scoreData[7] = parseInt(scoreData[7]);
}
function GameScore_getAwayTeam() { return this.scoreData[4]; }
function GameScore_getHomeTeam() { return this.scoreData[6]; }
function GameScore_isFinal() { return this.scoreData[2]=="final"; }
function GameScore_getHomeTeamScore() { return this.scoreData[7]; }
function GameScore_getAwayTeamScore() { return this.scoreData[5]; }
function GameScore_doesHomeTeamLead() { return this.scoreData[7]> this.scoreData[5]; }
function GameScore_doesAwayTeamLead() { return this.scoreData[5]> this.scoreData[7]; }
function GameScore_getWeekId() { return this.scoreData[12]; }
GameScore.prototype.getHomeTeam = GameScore_getHomeTeam;
GameScore.prototype.getAwayTeam = GameScore_getAwayTeam;
GameScore.prototype.isFinal = GameScore_isFinal;
GameScore.prototype.getHomeTeamScore = GameScore_getHomeTeamScore;
GameScore.prototype.getAwayTeamScore = GameScore_getAwayTeamScore;
GameScore.prototype.doesHomeTeamLead = GameScore_doesHomeTeamLead;
GameScore.prototype.doesAwayTeamLead = GameScore_doesAwayTeamLead;
GameScore.prototype.getWeekId = GameScore_getWeekId;
我只添加了一些访问器,因为我不需要大部分数据。您的需求可能会有所不同。