我正在尝试获取一些JSON数据。我可以在常规的Web浏览器中访问数据,例如:http://www.ebrent.net/apis/tsp.php?fund=G+Fund&start=2003-01-01&end=2004-01-01,但我无法在jQuery中使用它。我做错了什么?
请查看我的jsFiddle:https://jsfiddle.net/MrSnrub/mq31hwuj/
var tsp_api = '//www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01';
$.getJSON( tsp_api, function(json) {
// This alert never gets called.
alert("Success!");
// Set the variables from the results array
var data = json;
// console.log('Data : ', data);
// Set the div's text
$('#div-data').text(data);
});
答案 0 :(得分:1)
您无法获得结果,因为远程网站未启用CORS: 如果你看一下控制台,你会看到:
阻止跨源请求:同源策略禁止读取 远程资源在 http://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01。 (原因:CORS标题' Access-Control-Allow-Origin'缺失)。
您可以使用anyorigin.com之类的东西绕过CORS,即:
$.getJSON('http://anyorigin.com/get/?url=http%3A//www.ebrent.net/apis/tsp.php%3Fstart%3D2003-01-01%26end%3D2004-01-01&callback=?', function(data){
$('#div-data').html(data.contents);
});
答案 1 :(得分:0)
如果您在不使用https的情况下运行服务器,则此方法有效。注意fetchApi被用来代替jquery Library,因为它在浏览器中不可用
var tsp_api = 'https://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01';
function fetchData(url) {
return fetch(url, {
method: 'get'
}).then(function(response) {
return response.json();
}).catch(function(err) {
console.log(error);
});
}
fetchData(tsp_api).then((data)=> console.log(data)).catch((err)=> console.log(err));
这不会使用HTTPS在jsfiddle上工作,浏览器将拒绝通过HTTP加载任何资源。正如您所尝试的那样,将API URL更改为使用HTTPS而不是HTTP通常可以解决此问题。但是,您的ebrent.net不允许使用CoRS进行HTTPS连接。因此,您无法获得jsfiddle的结果