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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32672365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:35:57  来源:igfitidea点击:

Get data from JSON API and display it in HTML

javascriptjqueryhtmljson

提问by Agustín Covarrubias

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):

我正在尝试使用此minecraft 服务器 API (JSON)来显示在我的网页中,例如...现在有(玩家)已连接。JSON 文件如下所示(外部):

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

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

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

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

回答by Vladislav Karamfilov

You should change your AJAX success callback to:

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

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 spanelement - #playersinstead of #resultsand you're referencing the wrong JSON property - json.players.nowinstead of json.players.onlinelike in the sample response you provided.

问题是您选择了错误的span元素 -#players而不是#results您引用了错误的 JSON 属性 -json.players.now而不是json.players.online您提供的示例响应中的元素。

回答by Fabian Lurz

Datatype should be JSON.

数据类型应该是 JSON。

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

在此处查看此视频:https: //www.youtube.com/watch?v=fEYx8dQr_cQ

You should be fine then.

那你应该没问题。