簡體   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