让url中的Json数据想要输出到表中的html页面

时间:2018-03-11 22:53:11

标签: javascript html json fetch

我是一个完全的初学者,所以很简单,我在亚马逊AWS上有一个URL链接的Json代码,我希望能够获取数据并将其输出到HTML页面上的表格,你可以帮助我PLZ。正如您在下面的html代码中看到的那样,我希望从JS URL链接中的数据中提取JS代码和示例信息 代码

<!DOCTYPE html>

<html>
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="http://fonts.googleapis.com/css?family=Fjalla+One|Cantarell:400,400italic,700italic,700" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="styles.css">

<title>Convert JSON Data to HTML Table Example</title>
<style>
    table, th, td 
    {
        margin:10px 0;
        border:solid 1px #333;
        padding:2px 4px;
        font:15px Verdana;
    }
    th {
        font-weight:bold;
    }


  </style>
 </head>
 <body>

 <TITLE>"Country information"</TITLE>
 <h2>Country information </h2>

 <section class="content">
 <div class="row">
 <div class="box">
  <div class="box-body">
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
  </div>
</div>

<script>

var getJSON = function(url, callback) {

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';

xhr.onload = function() {

    var status = xhr.status;

    if (status == 200) {
        callback(null, xhr.response);
    } else {
        callback(status);
    }
};

xhr.send();
};

getJSON('https://url.json',  function(err, data) {

if (err != null) {
    console.error(err);
} else {

    var text = `Name: ${data.name}
 area: ${data.area}
 borders: ${data.borders}`

    console.log(text);
}
});

  `Sample json file on url I want to display in HTML
   {
   "name": "Angola",
  "altSpellings": [
    "AO",
    "República de Angola",
    "ʁɛpublika de an'ɡɔla"
  ],
  "area": 1246700,
  "borders": [
    "COG",
    "COD",
    "ZMB",
     "NAM"
   ],
  "callingCodes": [
    "244"
   ],
  "capital": "Luanda",
  "currencies": [
    "AOA"
   ],
  "demonym": "Angolan",
  "flag": "https://en.wikipedia.org/wiki/Flag_of_Angola#/media/File:Flag_of_Angola.svg",
  "ISO": {
    "alpha2": "AO",
    "alpha3": "AGO"
  },
  "languages": [
    "pt"
  ],
  "latlng": [
    -12.5,
    18.5
  ],
  "nativeName": "Angola",
  "population": 24383301,
  "region": "Africa",
  "subregion": "Middle Africa",
  "timezones": [
    "UTC+01:00"
  ],
  "translations": {
    "de": "Angola",
    "es": "Angola",
    "fr": "Angola",
    "ja": "アンゴラ",
    "it": "Angola"
  },
  "wiki": "http://en.wikipedia.org/wiki/angola",
  "hemisphere": [
    "Southern",
    "Eastern"
  ]
  },`

1 个答案:

答案 0 :(得分:0)

我使用这样的东西用JS来构建一个带有JSON的html表

var _table_ = document.createElement('table'),
      _tr_ = document.createElement('tr'),
      _th_ = document.createElement('th'),
      _td_ = document.createElement('td');
      _table_.classList.add('table')
      function buildHtmlTable(arr) {
          var table = _table_.cloneNode(false),
              columns = addAllColumnHeaders(arr, table);
          for (var i=0, maxi=arr.length; i < maxi; ++i) {
              var tr = _tr_.cloneNode(false);
              for (var j=0, maxj=columns.length; j < maxj ; ++j) {
                  var td = _td_.cloneNode(false);
                      cellValue = arr[i][columns[j]];
                  td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
                  tr.appendChild(td);
              }
              table.appendChild(tr);
          }
          return table;
      }
      function addAllColumnHeaders(arr, table)
      {
          var columnSet = [],
              tr = _tr_.cloneNode(false);
          for (var i=0, l=arr.length; i < l; i++) {
              for (var key in arr[i]) {
                  if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
                      columnSet.push(key);
                      console.log(columnSet)
                      var th = _th_.cloneNode(false);
                      th.appendChild(document.createTextNode(key));
                      tr.appendChild(th);
                  }
              }
          }
          table.appendChild(tr);
          return columnSet;
      }

然后我用返回的JSON运行它:

document.getElementById('yourDIV').appendChild(buildHtmlTable(res));

建立你的api请求:

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         // Response comes through here
      }
  };
  xhttp.open("GET", "/api/url/", true);
  xhttp.send();

然后,如果您只想将这3个对象推送到表中,请创建一个数组,然后使用这些对象构建表(未测试)

// Response comes through here
var obj = []
var data = xhttp.responseText
obj.push(data.name, data.area, data.borders)
document.getElementById('yourDIV').appendChild(buildHtmlTable(data));

查看我做过的这个JSfiddle示例:https://jsfiddle.net/7dvudr5q/5/