javascript - JSON 到 HTML 从 url

标签 javascript html json rest

我目前正在尝试学习 RESTful API 并将它们实现到用例中,我正在尝试做的一件事是将带有 json 有效负载的 url 从一台服务器加载到单独的 Web 服务器中,以显示在表上数据。我不太熟悉这个所以我试图找出最好的方法来做到这一点。

我正在使用此 API 发布到 domain.com/todos 页面

https://github.com/corylanou/tns-restful-json-api

然后我尝试使用它来将其打印到表格中 https://github.com/sam-suresh/JSON-URL-to-HTML-Table

但它看起来并不正常。我将它们全部放入一个索引文件中,它显示它在控制台上访问了我的 api,但我没有在表中显示任何输出。

<html>
<table id="personDataTable">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>due</th>
    </tr>

</table>

<style>
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
</style>
     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>
$.ajax({
    url: 'http://my-website-domain.com/todos',
    type: "get",
    dataType: "json",

    success: function(data) {
        drawTable(data);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
        row.append($("<td>" + rowData.id + "</td>"));
        row.append($("<td>" + rowData.name + "</td>"));
        row.append($("<td>" + rowData.due + "</td>"));
    }

</script>
</html>

这是它在/todos 页面上显示的内容

[{"id":1,"name":"Write presentation","completed":false,"due":"0001-01-01T00:00:00Z"},{"id":2,"name":"Host meetup","completed":false,"due":"0001-01-01T00:00:00Z"},{"id":3,"name":"New Todo","completed":false,"due":"0001-01-01T00:00:00Z"}

最佳答案

成功函数未传递原始数据。它传递了一个具有许多不同属性的对象。数据只是其中之一。试试这个:

$.ajax({
    url: 'http://my-website-domain.com/todos',
    type: "get",
    dataType: "json",

    success: function(results) {
        drawTable(results.data);
    }
});

也有可能是我记错了。我会在您的成功函数中放置一个调试器,看看它实际传递了什么,然后从那里开始。

关于javascript - JSON 到 HTML 从 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111406/

相关文章:

javascript - 如何在运行时在 extjs 中更改代理的 extraParams 配置?

javascript - 可点击的数据表行

java - Android:如何将 HttpResponse 转换为 List<Object>

php - json_encode 多系列流程图的 MySQL 查询

javascript - ajax 发送 POST 两次,从 PHP 接收双重/重复结果

javascript - 为什么当我使用 babel 将 ES6 编译为 ES5 时,浏览器需要一个 polyfills 文件

javascript - ngrx效果并行http调用

html - 我的 css 不适用于移动浏览器,但它适用于调整大小的桌面浏览器

html - 如何从顶部显示居中的div?

html - CSS:在文本字符后插入换行符