繁体   English   中英

使用Javascript从REST解析并显示JSON

[英]Parse and display JSON from REST using Javascript

我正在尝试使用javascript从显示在网页上的REST获取JSON数据,我有以下REST调用在firefox控制台上正常工作

function gethosts() {
   var xhttp = new XMLHttpRequest();
   xhttp.open("GET", "https://10.10.10.10/api/machine", false);
   xhttp.setRequestHeader("Content-type", "application/json");
   xhttp.send();
   var response = JSON.parse(xhttp.responseText);
}

JSON数据如下,

{
  "offset": 0,
    "hosts": [
     {
       "id": "422022c0-4ca7-66a2-bf73-9b56a65c9d2f",
       "name": "System Z",
       "type": "ORIGINAL",
       "model": "System X",
       "version": "Release 01",
       "management_ip": "10.10.10.11",
       "state": "ALIVE",
       "date": "2017-01-05T17:55:58Z"
},

我想用html显示

Name:    System Z
Model:   System X
Version: Release 01
MGMT IP: 10.10.10.11
State:   ALIVE

我尝试将其添加到函数中,但似乎不起作用

obj.hosts[0].name// return name
obj.hosts[0].model // return model
$( "body" ).append("<div>"+obj.hosts[0].name+"</div>")
$( "body" ).append("<div>"+obj.hosts[0].model+"</div>")

示例HTML代码是,

    <button type="button" onclick="gethosts()">Get all Hosts</button>   
    <div id="gethosts">Hosts: </div>

obj是从哪里来的? response是已解析的JSON。

function gethosts() {
   var xhttp = new XMLHttpRequest();
   xhttp.open("GET", "https://10.10.10.10/api/machine", false);
   xhttp.setRequestHeader("Content-type", "application/json");
   xhttp.send();
   var response = JSON.parse(xhttp.responseText);
   $("body").append("<div>"+response.hosts[0].name+"</div>")
   $("body").append("<div>"+response.hosts[0].model+"</div>")
}

另外,为什么要混合使用普通JS和jQuery? 如果已经加载了jQuery,为什么不使用$.ajax

暂无
暂无

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

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