3

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.

2
  • Questions should not be removed after they have been answered, someone may encounter the same problem and benefit from the post. Commented Jul 25, 2013 at 5:26
  • Do not vandalize or delete questions simply because they're solved. Commented Jul 29, 2013 at 6:09

2 Answers 2

4

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");
 });

});
Sign up to request clarification or add additional context in comments.

1 Comment

This is very useful, I am pleased to say that this works. Thanks for the help!
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.