2017-02-26 127 views
2

以下是我正在請求幫助的內容,目前我正在討論chatbot作爲我的第一個js項目,目前進展順利。我希望我的機器人能夠獲得特定的信息,例如玩家,然後將其發回給用戶。閱讀API的內容(JSON)

這裏的鏈接我從請求數據的API:https://minecraft-statistic.net/en/server/198.27.89.248_25629/json

我如何去從API獲取一個數據? 所有幫助表示讚賞。

+2

請給更多的信息 –

+2

你忘了問你的問題 –

回答

0
的「currentPlayers的價值

一些有用的方法給你: XMLHttpRequest(),JSON.parse()JSON.stringify()

使用並更改以下代碼以獲得您需要的迴應。

var xhr = new XMLHttpRequest(); 
xhr.open("get", "https://minecraft-statistic.net/en/server/198.27.89.248_25629/json"); 
xhr.setRequestHeader("accept", "application/json"); 
xhr.onload = function() { 
    var response = JSON.parse(xhr.responseText); 
    // list all objects 
    for (var key in response) { 
    console.log(key, response[key]); 
    } 
    // list players 
    console.log('players: ' + JSON.stringify(response['counter']['players'])); 
} 
xhr.send(); 

對於一個快速測試去到Firefox,按Shift+F4,粘貼並運行此檢查控制檯。

0

你的財產裝入一個對象從JSON

所以想象這是你的API的JSON

var json = {maxOnline: 8, currentPlayers: ["john", "steve", "bob"]} 

來,然後讓你可以使用這個語法

var players = json["currentPlayers"] 
console.log(players[0]); // outputs "john"