从 .json URL 获取数据并使用 Javascript/JQuery 在 HTML 中显示它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17620654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:04:02  来源:igfitidea点击:

Getting data from a .json URL and displaying it in HTML with Javascript/JQuery

javascripthtmljsonurl

提问by Maggy

I am trying to get json data from: http://api.dailymile.com/entries.jsonThen 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.

我正在尝试从以下位置获取 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>

Any help as to why it won't load the json data is appreciated.

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

回答by Kyle Fransham

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.

正如 aldux 所建议的,访问 JSON 跨域的一种简单方法是使用 JSONP。在您的情况下,服务器 (dailymile.com) 确实支持 JSONP,因此您只需添加一个 ?callback=? 参数到您的网址,即

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

});

回答by aldux

This is because the AJAX Same Origin Policy tha won't allow you to fetch data from different domains:

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

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

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

Try this instead:

试试这个:

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

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