Reputation: 55
I am trying to get json data from: http://api.dailymile.com/entries.json Then I wish to display this data in a table. The below code works when the json link points to a file already on my computer, but not when referring to a URL.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var entries = [];
var dmJSON = "http://api.dailymile.com/entries.json";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" + "<td>" + f.user.username + "</td>" + "<td>" + f.message + "</td>" + "<td> " + f.location + "</td>" + "<td>" + f.at + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>ID</th>
<th>UserName</th>
<th>Message</th>
<th>Location</th>
<th>Time</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
Any help as to why it won't load the json data is appreciated.
Upvotes: 3
Views: 29000
Reputation: 1879
As aldux suggests, a simple way of accessing JSON cross-domain is to use JSONP. In your case, the server (dailymile.com) does support JSONP, so you can simply add a ?callback=? parameter to your url, i.e.
var dmJSON = "http://api.dailymile.com/entries.json?callback=?";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" + "<td>" + f.user.username + "</td>" + "<td>" + f.message + "</td>" + "<td> " + f.location + "</td>" + "<td>" + f.at + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
Upvotes: 4
Reputation: 2804
This is because the AJAX Same Origin Policy tha won't allow you to fetch data from different domains:
http://en.wikipedia.org/wiki/Same_origin_policy
Try this instead:
http://en.wikipedia.org/wiki/JSONP
Upvotes: 1