【问题标题】:Retrieve JSON with StackOverflow API使用 StackOverflow API 检索 JSON
【发布时间】:2010-12-29 11:31:06
【问题描述】:

我想使用 API 从我的 Stack Overflow 配置文件中以 JSON 格式检索信息。

所以我使用这个链接http:/api.stackoverflow.com/1.0/users/401025/

但是当我发出请求时,我得到一个包含 JSON 数据的文件。 如何使用 Ajax 处理该文件?

这是我的代码 (http://jsfiddle.net/hJhfU/2/):

<html>
 <head>
  <script>
   var req;

   getReputation();

   function getReputation(){
      req = new XMLHttpRequest();
      req.open('GET', 'http://api.stackoverflow.com/1.0/users/401025/');
      req.onreadystatechange = processUser;
      req.send();
   }

   function processUser(){       
       var res = JSON.parse(req.responseText);
       alert('test');      
   }
  </script>
 </head>

警报从未触发,req.responseText 似乎为空。有什么想法吗?

【问题讨论】:

  • 使用 jQuery。手动 AJAX 让阅读你代码的人讨厌你,你很可能会犯错误。
  • @ThiefMaster 当你看到我更新的答案时你会笑的。

标签: javascript ajax stackexchange-api


【解决方案1】:

注意:您不能使用 Ajax 访问另一个域。 (这称为same-domain policy。)

不过,StackOverflow API 支持 JSONP 回调,所以这里有一个解决方案:

通过&lt;script&gt; 标签加载脚本。

创建一个执行此操作的函数:

function load_script(src) {
   var scrip = document.createElement('script');
   scrip.src = src;
   document.getElementsByTagName('head')[0].appendChild(scrip);
   return scrip; //just for the heck of it
}

设置回调函数:

function soResponse(obj) {
   alert(obj.users[0].reputation);
}

加载它!

load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse');

【讨论】:

  • @ArtWorkAD 首先,Ajax 不适用于 jsFiddle。其次,请参阅我的更新答案。
  • req.responseText 好像是空的
  • 这对我意味着什么?这是否意味着我无法使用 ajax 访问我的用户配置文件?
  • @ArtWorkAD 是的,就是这个意思。
  • @ArtWorkAD 看到我更新的答案,我想我解决了这个宝贝! :)
【解决方案2】:

有一个新的 API(替换 USER_ID)

https://api.stackexchange.com/2.2/users/[USER_ID]?&site=stackoverflow

【讨论】:

    【解决方案3】:

    对于任何未来的读者:

    我想在不使用 oAuth 和整个库的情况下获得我的声誉。感谢 Sebastien Horin 的回答,我可以轻松使用以下内容:

    function get_reputation() {
        const xhttp = new XMLHttpRequest();
        const url = 'https://api.stackexchange.com/2.3/users/USER_ID?&site=stackoverflow';
    
        xhttp.open( "GET", url );
        xhttp.send();
    
        xhttp.onreadystatechange = function() {
    
            if(xhttp.readyState == 4 && xhttp.status == 200) {
                
                var json = JSON.parse(xhttp.responseText);
                
                console.debug( json );
                
            }       
        }
    }
    
    get_reputation();
    

    注意:这里使用 API v2.3。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多