【发布时间】: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