如何从json获取数据并在html中显示

问题描述 投票:0回答:6

我是初学者,有个问题想请教大家

例如,我获取 JSON 的 URL 是:

返回的JSON为:

{
"Data":{
"id": 1312,
"Name": "Steem Dollars",
"Symbol": "SBD",
"website_slug": "steem-dollars",
"Level": 313,
"circulating_supply": 15185862.0,
"total_supply": 15185862.0,
"max_supply":null,
Quotes: {
"Dollar": {
"Price": 1.2369,
"volume_24h": 660195.0,
"market_cap": 18783392.0,
"percent_change_1h": 0.84,
"percent_change_24h": - 5.87,
"percent_change_7d": -10.61
}
},
"last_updated": 1529462954
},
"Metadata":{
"time stamp": 1529462906,
"Error": null
}
}

如何通过 https://api.coinmarketcap.com/v2/ticker/1312/ 获取 HTML 中的信息并在 HTML 中显示以下字段:

  • 名字
  • 符号
  • 排名
  • 价格
  • 成交量_24小时
  • 市值
  • Percent_change_1h
  • Percent_change_24h
  • Percent_change_7d

谁能给个例子,再次感谢。

html json
6个回答
1
投票

您可以使用Fetch API,这样您就不必依赖其他库,您可以执行类似的操作。

您还需要了解对象在 JavaScript 中如何工作。

function getElement(id) {
  return document.getElementById(id);
}

fetch('https://api.coinmarketcap.com/v2/ticker/1312/')
.then(res => res.json())
.then((res) => {
  const data = res.data;
  getElement('name').innerHTML =  'Name: ' + data.name;
  getElement('symbol').innerHTML = 'Symbol: ' + data.symbol;
  getElement('rank').innerHTML = 'Rank: ' + data.rank;
  getElement('price').innerHTML = 'Price: ' + data.quotes.USD.price;
  // do the rest here
});
<div>
  <p id="name"></p>
  <p id="symbol"></p>
  <p id="rank"></p>
  <p id="price"></p>
</div>


1
投票

Javascript方式:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("name").innerHTML = myObj.data.name;
    }
};
xmlhttp.open("GET", "https://api.coinmarketcap.com/v2/ticker/1312/", true);
xmlhttp.send();
<div id="name"></div>


1
投票

另一个解决方案是在 json 文件中的每个键上运行并将其设置为相同的 id 名称。

  $.getJSON( "resources/screenText.json", function( data ) {
      $.each( data, function( key, val ) {
        $( `#${key}`).html(val);
      });
    });

jQuery.getJSON()

screenText.json:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

html:

<span id="one"></span>
<span id="two"></span>
<span id="three"></span>

0
投票

为此我推荐 jQuery。它可以很好地处理 JSON。

$( document ).ready(function() {
	var url = "https://api.coinmarketcap.com/v2/ticker/1312/";
	$.getJSON( url, {
  	format: "json"
	})
  .done(function( data ) {
     $("#iid").text(data.data.id);
     $("#name").text(data.data.name);
  });
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script></script>

<div id="iid"></div>
<div id="name"></div>


0
投票

JSON 基本上是层次结构。因此,为了访问特定属性,您需要一步一步进行。

您可以使用Jquery进行ajax调用。

所以总结你的整个代码看起来像这样

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("https://api.coinmarketcap.com/v2/ticker/1312/",                      
     function(json, status){

            var data = json.data;
            var quotes = data.quotes;
            var usd = quotes.USD;


            console.log(JSON.stringify(quotes));
            console.log(JSON.stringify(data.name));
            console.log(JSON.stringify(quotes));

            $("#container").append(data.name+"<br>");

        });
    });
});
</script>
</head>
<body>

<button>Get Data</button>

<div id="container" ></div>

</body>
</html>

0
投票

这是另一种解决方案

HTML(index.html):

<!DOCTYPE html>
<html>
<head>
  <title>Display JSON Data</title>
</head>
<body>
  <ul id="myData"></ul>
  <script src="script.js"></script>
</body>
</html>

JavaScript(script.js):

fetch('data.json')
  .then(response => response.json())
  .then(data => {
    const dataList = document.getElementById('myData');
    data.forEach(item => {
      const listItem = document.createElement('li');
      listItem.textContent = item.name;
      dataList.appendChild(listItem);  

    });
  });

JSON(数据.json):

[
  {"name": "Alice"},
  {"name": "Bob"},
  {"name": "Charlie"}
]
© www.soinside.com 2019 - 2024. All rights reserved.