繁体   English   中英

将 JSON 从 URL 格式化为 HTML

[英]formatting JSON from URL into HTML

我如何获取从 URL 输出的 JSON 并将其格式化为 html。 我拥有的 JSON 如下所示:

prtg-version    "xxxxxxx"
treesize    0
channels    
0   
name    "Downtime"
name_raw    "Downtime"
lastvalue   ""
lastvalue_raw   ""
1   
name    "Execution Time"
name_raw    "Execution Time"
lastvalue   "19 msec"
lastvalue_raw   19
2   
name    "File count"
name_raw    "File count"
lastvalue   "431 #"
lastvalue_raw   431
3   
name    "Folder Size"
name_raw    "Folder Size"
lastvalue   "224,855,871 Byte"
lastvalue_raw   224855871
4   
name    "Newest File"
name_raw    "Newest File"
lastvalue   "1 s"
lastvalue_raw   1
5   
name    "Oldest File"
name_raw    "Oldest File"
lastvalue   "1 h 31 m"
lastvalue_raw   5476

它每 15 秒更新一次。 我想格式化成一个 html 表并删除一些批量。 我已经尝试了 w3schools 的一些代码,但这只是返回: [object Object],[object Object]

我的代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("https://myurl/api/table.json?blahblahblah", function(result){
      $.each(result, function(i, field){
        $("div").append(field + " ");
      });
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>

<div></div>

</body>
</html>

field是对您正在循环的对象的引用。 将其输出到 DOM 会将其强制转换为字符串,因此您会看到[object Object]输出。

要解决此问题,您需要访问对象属性并构建要输出的 HTML。 另请注意,从对象的上下文和您的代码来看,您应该循环遍历result.channels ,而不是result 尝试这个:

 var result = [{ 'prtg-version': "xxxxxxx", treesize: 0, channels: [{ name: "Downtime", name_raw: "Downtime", lastvalue: "", lastvalue_raw: "" }, { name: "Execution Time", name_raw: "Execution Time", lastvalue: "19 msec", lastvalue_raw: 19 }, { name: "File count", name_raw: "File count", lastvalue: "431 #", lastvalue_raw: 431 } // more data... ] }] jQuery(function($) { $("button").click(function() { // AJAX code removed from this demo, as it obviously cannot work // $.getJSON("https://myurl/api/table.json?blahblahblah", function(result){ $.each(result[0].channels, function(i, field) { $("div").append(`<p>${field.name}</p>`); }); // }) }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <button>Get JSON data</button> <div></div>

暂无
暂无

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

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