简体   繁体   English

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

[英]How do I get data from json and show it in html

I am a beginner and there is a question I would like to ask everyone我是初学者,有个问题想请教大家

For example, my URL to get JSON is:例如,我获取 JSON 的 URL 是:

The returned JSON is:返回的 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
}
}

How do I get information in HTML through https://api.coinmarketcap.com/v2/ticker/1312/ and display the following fields in the HTML:如何通过https://api.coinmarketcap.com/v2/ticker/1312/获取 HTML 中的信息并在 HTML 中显示以下字段:

  • name姓名
  • symbol象征
  • rank
  • price价钱
  • Volume_24h Volume_24h
  • Market_cap市值
  • Percent_change_1h Percent_change_1h
  • Percent_change_24h Percent_change_24h
  • Percent_change_7d Percent_change_7d

Who can give an example, Thanks again.谁能举个例子,再次感谢。

Javascript Way: 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>

I'd recommend jQuery for this.我会为此推荐jQuery。 It handles JSON well.它可以很好地处理 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>

You can use the Fetch API so you don't have to rely on other libraries, you can do something like.您可以使用Fetch API,因此您不必依赖其他库,您可以执行类似的操作。

You also need to know how an object works in JavaScript.您还需要了解对象在 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>

JSON are basically in hierarchy structure. JSON 基本上是层次结构。 So in order to access specific attribute you need to go step by step.因此,为了访问特定属性,您需要逐步进行。

You can use Jquery for ajax call.您可以使用 Jquery 进行 ajax 调用。

So summing up your whole code looks like this所以总结你的整个代码看起来像这样

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

another solution is to run on each key in the json file and set it to the same id name .另一种解决方案是在 json 文件中的每个键上运行并将其设置为相同的 id name 。

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

see jQuery.getJSON()jQuery.getJSON()

screenText.json : screenText.json :

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

html: html:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM