javascript - Iterate through a JSON list with JS function -
i'm looking way append json results, i'm working list (array?) , there's multiple elements, know can add styling directly in js code i'm more comfortable method. how can iterate through elements , implement in divs, create similar divs next elements.
the way achieve goal afaik this:
$("#article").append(data[i].datetime + data[i].headline + "<br />" + "<hr />" + data[i].summary);
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>project js 02</title> <link rel="stylesheet" href="assets/main.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div class="container container-table"> <div class="row vertical-center-row"> <div class="col-md-4 col-md-offset-4"> <button type="submit" class="btn btn-primary" style="width: 100%" class="search" id="getnews">get news!</button> <h1 id="headline"></h1><br> <h3 id="datetime"></h3><br> <div id="summary"></div><br> <h6 id="source"></h6><br> </div> </div> </div> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script> document.getelementbyid("getnews").addeventlistener("click", function () { var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news" $.getjson(newsurl, function (data) { for (i in data) { $("#headline").append(data[i].headline); $("#datetime").append(data[i].datetime); $("#summary").append(data[i].summary); $("#source").append(data[i].source); } }) }) </script> </body> </html>
you can creating elements (with jquery) needed, , appending them container:
$("#getnews").on("click", function () { var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news" $('#data').text("...loading..."); $.getjson(newsurl, function (data) { $('#data').html(""); data.foreach(function (article) { $('#data').append( $('<h1>').text(article.headline), $('<h3>').text(article.datetime), $('<div>').text(article.summary), $('<h6>').text(article.source) ); }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn btn-primary search" style="width: 100%" id="getnews">get news!</button> <div id="data"></div>
wiki
Comments
Post a Comment