繁体   English   中英

将JSON转换为HTML表

[英]Convert JSON to HTML Table

我试图将JSON从URL转换为HTML表,但是结果是HTML表变为空白。

我将JSON文件存储在http://bayuyanuargi.000webhostapp.com/myfile.json中 ,以下是我使用的代码:

 <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script> $(function() { var result = []; var dmJSON = "http://bayuyanuargi.000webhostapp.com/myfile.json?callback=?"; $.getJSON(dmJSON, function(data) { $.each(data.result, function(i, f) { var tblRow = "<tr>" + "<td>" + f.address.name + "</td>" + "<td>" + f.address.street + "</td>" + "</tr>" $(tblRow).appendTo("#resultdata tbody"); }); }); }); </script> </head> <body> <div class="wrapper"> <div class="profile"> <table id="resultdata" border="1"> <thead> <th>Name</th> <th>Street</th> </thead> <tbody> </tbody> </table> </div> </div> </body> </html> 

?callback=的存在使jQuery将请求作为JSONP执行。 您的页面仅返回JSON,而不返回JSONP

jQuery.getJSON()文档

JSONP如果URL包含字符串“ callback=? ”(或类似值,由服务器端API定义),则该请求将被视为JSONP。 有关更多详细信息,请参见$.ajax()中有关jsonp数据类型的讨论。

解决方案:删除callback=? 从URL。

 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(function() { var CORS = "https://cors-anywhere.herokuapp.com/" // for testing purposes, only var result = []; var dmJSON = CORS + "https://bayuyanuargi.000webhostapp.com/myfile.json"; $.getJSON(dmJSON, function(data) { $.each(data.result, function(i, f) { var tblRow = "<tr>" + "<td>" + f.address.name + "</td>" + "<td>" + f.address.street + "</td>" + "</tr>" $(tblRow).appendTo("#resultdata tbody"); }); }); }); </script> </head> <body> <div class="wrapper"> <div class="profile"> <table id="resultdata" border="1"> <thead> <th>Name</th> <th>Street</th> </thead> <tbody> </tbody> </table> 

注意:返回JSON(不是JSONP)的常规Ajax调用受常规CORS限制 我在上面的演示中添加了一种变通方法,仅用于演示目的。 在您的具体情况下,可以将页面/脚本部署在服务器的同一主机上,或者将必要的标头添加到服务器

暂无
暂无

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

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