Reputation: 71
I have tried to convert my JSON from URL to HTML Table, but the result is the HTML table went blank.
I stored the JSON file in http://bayuyanuargi.000webhostapp.com/myfile.json, below is the code I used:
<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>
Upvotes: 1
Views: 2909
Reputation: 135822
The presence of ?callback=
makes jQuery perform the request as JSONP. And your page returns JSON only, not JSONP.
JSONP If the URL includes the string "
callback=?
" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of thejsonp
data type in$.ajax()
for more details.
Solution: Remove the callback=?
from the 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. 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.
Upvotes: 2