从URL的JSON转换为HTML [英] JSON to HTML from url

查看:49
本文介绍了从URL的JSON转换为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习RESTful API并将其实现为用例,而我要做的一件事是将带有json有效负载的url从一台服务器加载到单独的Web服务器上以显示在表上数据.我对此不太熟悉,因此我正在尝试找出最佳方法.

I am currently trying to learn RESTful API's and implementing them into use case and one of the things I am trying to do is to load the url with the json payload from one server into a separate web server to display on a table the data. I am not too familiar with this so I am trying to find out the best way to do this.

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

I am using this API to post to a page which is domain.com/todos

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

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

And then I am attempting to use this to print it out to a table https://github.com/sam-suresh/JSON-URL-to-HTML-Table

,但看起来不起作用.我将它们全部放入一个索引文件中,它显示它在控制台上击中了我的api,但未在表中显示任何输出.

but it doesn't look like it is working. I put it all into a single index file and it shows it hitting my api on the console but I am not showing any output in the table.

<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页面上显示的内容

And this is what it shows on the /todos page

[{"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"}

推荐答案

谢谢大家的帮助.问题是未启用CORS策略,因此请求被阻止.解决方法是通过添加

Thank you all for all of the help. The issue was that the CORS policy wasn't enabled so the request was getting blocked. The fix was to simply enable CORS which was done in the handlers.go for this particular API by adding

w.Header().Set("Access-Control-Allow-Origin", "*")

这篇关于从URL的JSON转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆