stackexchange API - 按用户nick获取用户ID

时间:2014-09-21 21:41:14

标签: javascript stackexchange-api

我想通过stackoverflow获取用户的活动,如here所示,但问题是,它只接受用户的ID。我想通过用户昵称来做 only ,所以任何人都可以写下他的昵称并获得统计数据。 API似乎不支持通过提供缺口来获取用户ID。

是否有任何解决方法可以通过用户名获取用户的ID?谢谢。

1 个答案:

答案 0 :(得分:0)

我通过在YQL的帮助下从stackoverflow/users删除响应来破解我的方式,以便通过AJAX跨域获取页面。这是粗略的代码:http://jsbin.com/teguho/1/edit

HTML

<input>
<div></div>

的Javascript

var idCont = $('div'),
    input = $('input');

// input events
input.on('blur', function(){
  doAjax(this.value);
}).on('keydown', function(e){
  if (e.keyCode == 13)
    doAjax(this.value);
});


function doAjax(url){
  url = 'http://stackoverflow.com/users/filter?search=' + url;
  if(url.match('^http')){
    idCont.html('fetching...');
    $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
              "q=select%20*%20from%20html%20where%20url%3D%22"+
              encodeURIComponent(url)+
              "%22&format=xml'&callback=?",
              function(data){
      idCont.empty();
      if(data.results[0]){
        data = filterData(data.results[0]);
        getIDs( $('<div>').html(data) );
      }
    }
             );
  }
}

// clean up the response
function filterData(data){
  data = data.replace(/<?\/body[^>]*>/g,'')
  .replace(/[\r|\n]+/g,'')
  .replace(/<--[\S\s]*?-->/g,'')
  .replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'')
  .replace(/<script[^>]*>[\S\s]*?<\/script>/g,'')
  .replace(/<script.*\/>/,'');
  return data;
}

// scrap the DOM for the user's IDs
function getIDs( elm ){
  var IDs = '';
  elm.find('.user-info').each(function(){
    var id = $(this).find('a:first')[0].href.split('/').reverse()[1];
    IDs += id + '<br>';
  });

  idCont.html(IDs);
}