无法从Github获取JSON

时间:2014-07-10 16:24:25

标签: ajax json git

我还在学习如何跨域提取信息,更不用说AJAX / JSON了,我在从github获取JSON文件时遇到了麻烦。 (之前从未这样做过)

我一直在阅读有关跨域的安全问题,我正在尝试使用headerjsonp解决此问题,但似乎没有任何工作。

这是我到目前为止的尝试(对此我很抱歉,如果这是一次糟糕的尝试,对不起)

$( document ).ready(function() {
   var ID = "aanders50/0c190f846790c9b05691";
   $.ajax({
       url: 'https://gist.github.com/'+ID,
       type: 'GET',
       dataType: 'json',
       data: { 
       },
       headers: {
           'Access-Control-Allow-Origin': '*'
       },
       success: function (json) {
           alert(JSONurl = 'https://gist.github.com/' + ID);
           alert(json[ID].id);
           alert(json[ID].name);
           alert(json[ID].summonerLevel); 
       },
       error: function (XMLHttpRequest, textStatus, errorThrown) {
           alert("error");
       }
   });
});

我一直在寻找一段时间,但我觉得我错过了一些我找不到的东西,这使得实际上难以找到答案.. :(

错误 enter image description here

XMLHttpRequest cannot load https://gist.github.com/aanders50/0c190f846790c9b05691. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56087' is therefore not allowed access.

GET http://localhost:56087/1f950c50642c41cfa5690a661fc548db/arterySignalR/ping?…http%3A%2F%2Flocalhost%3A56087%2FEvents&browserName=Chrome&_=1405009417830 404 (Not Found) 

Git文件 enter image description here The File

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

  

我一直在阅读有关跨域的安全问题,我试图通过使用header或jsonp来修复此问题,但似乎没有任何工作。

Access-Control-Allow-Origin是响应头,而不是请求头。如果您可以授予自己从服务器读取数据的权限,那将是毫无意义的。您无法为正在使用的URL设置响应标头,因为您无法控制服务器; Github做。

您无法使用JSONP。您请求的文档是HTML文档,而不是JSONP脚本。 (请注意,这也意味着您无法将其解析为JSON)。

如果你想获取页面,那么你需要使用一个代理(例如,向你自己的服务器发出Ajax请求并让它为你提取数据)。

答案 1 :(得分:0)

您的文件https://gist.github.com/aanders50/0c190f846790c9b05691需要支持jsonp并返回JSON响应,以便您在此域外使用它。

只需在AJAX请求中添加标题就无济于事。