[英]Using jQuery to get JSON Data
我有一个显示如下的JSON响应:
{
"gameId": 2540832082,
"mapId": 12,
"gameMode": "ARAM",
"gameType": "MATCHED_GAME",
"gameQueueConfigId": 65,
"participants": [
{
"teamId": 100,
"spell1Id": 32,
"spell2Id": 7,
"championId": 25,
"profileIconId": 774,
"summonerName": "MLG Elan",
"bot": false,
"summonerId": 77477471,
"runes": [],
"masteries": [
{
"rank": 5,
"masteryId": 6111
},
{
"rank": 1,
"masteryId": 6122
},
{
"rank": 2,
"masteryId": 6131
}
]
},
{
"teamId": 100,
"spell1Id": 4,
"spell2Id": 32,
"championId": 120,
"profileIconId": 774,
"summonerName": "Nuetzlich",
"bot": false,
"summonerId": 43800105,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 3,
"masteryId": 6114
},
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6322
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 5,
"masteryId": 6351
},
{
"rank": 1,
"masteryId": 6362
}
]
},
{
"teamId": 100,
"spell1Id": 13,
"spell2Id": 7,
"championId": 67,
"profileIconId": 19,
"summonerName": "Sonicmońgrel",
"bot": false,
"summonerId": 82267777,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6323
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 4,
"masteryId": 6351
}
]
},
我正在努力获取每个玩家的“ summonerNames”并将其显示在网站上:(
我需要什么jQuery?
这就是获取数据的方式:
function getCurrentGame(summonerID) {
$.ajax({
url: "https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/" + summonerID + "?api_key=" + APIKEY,
type: 'GET',
dataType: 'json',
data: {
},
我在这里需要什么:
success: function (resp) {
}
要显示召唤者的名字?
我在HTML中有此功能,可以根据名称简单地建立列表:
Current Players (<span id="listPlayers"></span>)
<hr />
<span id="playerNames"></span>
随意修改它,我真的不知道如何列出玩家的名字:(
谢谢!!!
您的整个JSON对象就是resp。
假设您要访问"gameMode": "ARAM"
,它将是resp.gameMode
。
让我们想访问"summonerName": "MLG Elan"
,它将是resp.participants.summonerName
(因为resp.participants.summonerName
在称为参与者的数组中)
尝试这个
var obj = jQuery.parseJSON( resp );
alert( obj.participants[0].summonerName);
在您的json data.participants
是一个数组,您可以使用Array#map
获取所有名称:
var names = data.participants.map(function(item) {
return item.summonerName;
});
你不需要jquery
的
JSON格式
var json = yourJSON;
的JavaScript
var lenght = json.participants.length;
var summonerName = "";
for (i = 0; i < lenght ; i++){
summonerName += json.participants[i].summonerName.toString() + ", ";
}
document.getElementById("playerNames").innerText = summonerName;
的HTML
<span id="playerNames"></span>
resp参数是由返回的Json创建的JavaScript对象。 summonerName是每个参与者的属性,而参与者是对象的数组。 因此,您需要遍历参与者数组并获取每个参与者的名称。 试试这个
success: function (resp) {
var participants = resp.participants,
names = "",
spanElement = document.getElementById("playerNames");
participants.forEach(function(part){
names = names + part.summonerName + " ";
}
spanElement.innerText = names ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.