如何通过JavaScript获取Steam昵称

时间:2019-05-25 01:36:48

标签: javascript php steam-web-api

你好,我现在使用此php代码获取蒸汽昵称

function EchoPlayerName($steamid){
    $xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
    if(!empty($xml)) {
        $username = $xml->steamID;
        echo $username;
    }
}

$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];

但是我这个用于列出播放器和加载页面的速度很慢 所以我想在整个加载页面后通过javascript加载数据

有什么想法吗?

API示例

{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #.","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}

1 个答案:

答案 0 :(得分:0)

首先,您应该使用纯JavaScript或jquery的ajax获取数据。然后,您应该定位要使用此检索到的数据填充的HTML元素。想象一下ID为target的元素。

jQuery:

$(document).ready(function () {
    $.ajax({
        url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
    }).done(function (data) {
        var json = JSON.parse(data);
        $('#target').text(json['response']['players'][0]['personaname']);
    });
});

纯javascript:

var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
    xhr.onload = function () {
        if (xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
        } else {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();

请记住将这些脚本放在文档的末尾。