Get data from JSON API and display it in HTML

我的未来我决定 提交于 2021-02-08 10:09:57

问题


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 }

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...


回答1:


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');
}

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.




回答2:


Datatype should be JSON.

Check this video here: https://www.youtube.com/watch?v=fEYx8dQr_cQ

You should be fine then.



来源:https://stackoverflow.com/questions/32672365/get-data-from-json-api-and-display-it-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!