3

我正在尝试从以下位置获取 json 数据: http ://api.dailymile.com/entries.json 然后我希望在表格中显示这些数据。以下代码在 json 链接指向我计算机上已有的文件时有效,但在引用 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>

任何关于为什么它不会加载 json 数据的帮助表示赞赏。

4

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

});
于 2013-07-12T17:49:27.927 回答
1

这是因为 AJAX 同源策略不允许您从不同域获取数据:

http://en.wikipedia.org/wiki/Same_origin_policy

试试这个:

http://en.wikipedia.org/wiki/JSONP

于 2013-07-12T17:41:12.690 回答