【问题标题】:Parse and display JSON from REST using Javascript使用 Javascript 从 REST 解析和显示 JSON
【发布时间】:2017-01-05 23:33:54
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

    标签: javascript html json ajax rest


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多