无法调用 getJSON 方法获取数据

Cannot call getJSON method to fetch data

我正在尝试获取一些 JSON 数据。我可以在常规网络浏览器中正常访问数据,如下所示: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);

});

您无法获取结果,因为远程站点未启用 CORS: 如果您查看控制台,您会看到:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01. (Reason: CORS header 'Access-Control-Allow-Origin' missing).


您可以使用 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);
});

如果您 运行 您的服务器不使用 https,则此方法有效。请注意,使用 fetchApi 而不是 jquery 库,因为它在浏览器中不可用

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

的结果