Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
Questions should not be removed after they have been answered, someone may encounter the same problem and benefit from the post. –  apaul34208 Jul 25 at 5:26
 
Do not vandalize or delete questions simply because they're solved. –  Flexo Jul 29 at 6:09

2 Answers

up vote 1 down vote accepted

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

});
share|improve this answer
 
This is very useful, I am pleased to say that this works. Thanks for the help! –  Maggy Jul 12 at 18:03

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

share|improve this answer
 
Thanks for your help, I did not know about this. –  Maggy Jul 12 at 18:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.