我正在尝试将内容从托管在外部服务器上的json文件中提取到html中。 这是我到目前为止所取得的成就。
var myurl = "https://gist.github.com/Keeguon/2310008/raw/865a58f59b9db2157413e7d3d949914dbf5a237d/countries.json";
$(document).ready(function () {
$.getJSON(myurl,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + json[i].code + "</td>");
$('table').append(tr);
}
});
});
非常感谢任何帮助!
答案 0 :(得分:2)
你有两个问题:
我建议使用Github API here along with a JSONP request。我还建议您使用链接到的this fork of the gist。考虑到这一点:
$.ajax({
url: 'https://api.github.com/gists/7748738',
dataType: 'jsonp',
success: function (response) {
var countriesStr = response.data.files['countries.json'].content
, countries = JSON.parse(countriesStr);
// countries is an array of countries.
}
});
答案 1 :(得分:0)
对Andrew Whitaker来说,JSON无效。键必须用字符串括起来。
{'name': 'Afghanistan', code: 'AF'},
...
此外,出于安全原因,默认情况下会阻止将XMLHttpRequest设置为与您的网站所在域不同的域。因此,在进行跨域请求时,您需要做一些不同的事情。这是一个使用CORS的精彩教程。
引用docs:
常规网页可以使用XMLHttpRequest对象发送和 从远程服务器接收数据,但它们受到相同的限制 原产地政策。扩展不是那么有限。扩展可以与之交谈 只要它首次请求,它的原点以外的远程服务器 跨域权限。