Getting data from a .json URL and displaying it in

2019-07-07 01:16发布

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条回答
来,给爷笑一个
2楼-- · 2019-07-07 01:54

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

查看更多
戒情不戒烟
3楼-- · 2019-07-07 02:11

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

});
查看更多
登录 后发表回答