[英]Convert JSON to HTML Table
I have tried to convert my JSON from URL to HTML Table, but the result is the HTML table went blank. 我试图将JSON从URL转换为HTML表,但是结果是HTML表变为空白。
I stored the JSON file in http://bayuyanuargi.000webhostapp.com/myfile.json , below is the code I used: 我将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>
The presence of ?callback=
makes jQuery perform the request as JSONP. ?callback=
的存在使jQuery将请求作为JSONP执行。 And your page returns JSON only, not JSONP . 您的页面仅返回JSON,而不返回JSONP 。
From jQuery.getJSON() docs : 从jQuery.getJSON()文档 :
JSONP If the URL includes the string "
callback=?
" (or similar, as defined by the server-side API), the request is treated as JSONP instead.JSONP如果URL包含字符串“
callback=?
”(或类似值,由服务器端API定义),则该请求将被视为JSONP。 See the discussion of thejsonp
data type in$.ajax()
for more details.有关更多详细信息,请参见
$.ajax()
中有关jsonp
数据类型的讨论。
Solution: Remove the callback=?
解决方案:删除
callback=?
from the URL. 从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>
Note: Regular Ajax calls that return JSON (not JSONP) are subject to regular CORS restrictions . 注意:返回JSON(不是JSONP)的常规Ajax调用受常规CORS限制 。 I have added a workaround in the demo above just for demonstrations purposes.
我在上面的演示中添加了一种变通方法,仅用于演示目的。 In your concrete case, either deploy the page/script at the same host of the server, or add the necessary headers to the server .
在您的具体情况下,可以将页面/脚本部署在服务器的同一主机上,或者将必要的标头添加到服务器 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.