从JSON API获取数据并以HTML显示

问题描述:

我正在尝试使用此 minecraft服务器API(JSON),以在我的网页中显示类似...的内容.目前已连接(玩家).JSON文件如下所示(外部):

I'm trying to use this minecraft server API (JSON), to show in my webpage, something like... Right now there are (players) connected. The JSON file looks like this (external):

{
"status": true,
"players": {
    "online": 534,
    "max": 900
},
"cache": 1442690473 }

我想获取数据播放器(在线),并将其显示在html段落上....使用JavaScript或Jquery.我使用 getJSON 搜索了一些解决方案,但无法使其工作..我尝试使用AJAX发出请求...

I want to fetch the data players (online) and display it on a html paragraph.... Using JavaScript or Jquery. I searched some solutions, using getJSON, but I couldn't make it work.. I tried using AJAX to make a request...

  // AJAX Request to JSON
              $.ajax({
                  url: "https://mcapi.ca/query/mythalium.com/players",
                  // Handle as Text
                  dataType: "text",
                  success: function(data) {
                      // Parse JSON file
                      var json = $.parseJSON(data);
                      //Store data into a variable
                      // Display Players
                      $('#players').html('Currently there are: ' + json.players.now ' users');
                  }
      });

然后使用以下命令显示它:

And then display it using:

 <span id="results"></span>

为什么不起作用?什么都没有显示...

Why is not working? Nothing is being showed...

您应将AJAX成功回调更改为:

You should change your AJAX success callback to:

success: function(data) {
    // Parse JSON file
    var json = $.parseJSON(data);
    //Store data into a variable
    // Display Players
    $('#results').html('Currently there are: ' + json.players.online' + users');
}

问题在于您选择了错误的 span 元素- #players 而不是 #results ,并且引用了错误的JSON属性- json.players.now 而不是 json.players.online ,就像您提供的示例响应中一样.

The problems are you're selecting the wrong span element - #players instead of #results and you're referencing the wrong JSON property - json.players.now instead of json.players.online like in the sample response you provided.