我正在尝试建立一个网站,以一种简洁的方式显示此API提供的信息。我已经完成了设计,但现在我需要实际获取这些信息。我想得到的信息来自https://api.roleplay.co.uk/v1/player/xxx,我可能想要在下面的代码中替换h1中的'...'来自API的“name”位。我该怎么做呢?我对JS一无所知,我更喜欢通过实际操作来学习。这是我的相关代码片段:
<div class=playerdata>
<div class=head>
<h1 id="playerName">...</h1>
<h2>'STEAMID'</h2>
<button>Steam Profile</button>
<button>Forum Profile</button>
<button>Report</button>
<button>Recommend</button>
</div>
你可以使用jQuery进行这样的调用:
$.getJSON(' https://api.roleplay.co.uk/v1/player/76561198062083666', function(data) {
$('#playerName').html(data.name);
});
data包含来自API的所有JSON信息,以及jQuery / pure Javascript,您可以使用它。
$('#playerName').html(data.name)
像这样改变你的h1
<h1 id="playerName">...</h1> to <h1 id="playerName">jim</h1>
从...到吉姆
我的JSFiddle:https://jsfiddle.net/calinvlasin/dn5fhqfa/1/
我更喜欢通过实际操作来学习
只是一种方式来说,给我解决方案,然后我会试着弄明白,但没关系,人们以不同的方式学习。
我更新了你的HTML,因此从JavaScript中引用它更容易,我不知道report
和recommend
功能是如何工作的,因为它们不在API中。
<body>
<div class="playerdata">
<div class="head">
<h1 id="playerName">...</h1>
<h2 id="steamId">'STEAMID'</h2>
<button id="steamProfile">Steam Profile</button>
<button id="forumProfile">Forum Profile</button>
<button id="report">Report</button>
<button id="recommend">Recommend</button>
</div>
</div>
<script type="text/javascript">
function httpGetJSON(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return JSON.parse(xmlHttp.responseText);
}
var player = httpGetJSON("https://api.roleplay.co.uk/v1/player/76561198062083666");
document.getElementById('playerName').innerHTML = player.name;
document.getElementById('steamId').innerHTML = player.steamid;
document.getElementById('steamProfile').addEventListener('click', function(){
window.location.href = player.steam.profileurl
})
document.getElementById('forumProfile').addEventListener('click', function(){
window.location.href = player.forumurl
})
</script>
<body>
这应该给你一个模板来使用