SHESHUI.ME

通过Json跨域调用Twitter

/

之前用过这个方法,最近发现这方法好像不好使了,无法读出任何数据。当然,即使采用此方法,也需要保证你的域处于墙外,否则肯定不好使。

1. twitter_json.php API接口文件

<?php
$call=trim(urlencode($_REQUEST['callback']));
$user=trim(urlencode($_REQUEST['username']));
$count=trim(urlencode($_REQUEST['count']));
//echo $call.'('.file_get_contents('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$user.'&count='.$count).')';
echo $call.'('.file_get_contents('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$user.'&count='.$count).')';
?>

2. get_twitter.js 处理接收数据的JS文件

//用来处理twitter API 返回的JSON数据
function getTwitter(twitters) {
  var statusHTML = [];     
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    if (i%2==0){
      statusHTML.push('<li class="tweet odd">'+status+'<span class="time">'+relative_time(twitters[i].created_at)+'</span></li>');
    } else{
      statusHTML.push('<li class="tweet even">'+status+'<span class="time">'+relative_time(twitters[i].created_at)+'</span></li>');
    }
  }
  //if (statusHTML == ''){statusHTML.push('<li>Following me On Twitter...</li>')}
  document.getElementById('twitter-loading').style.display="none";
  document.getElementById('twitter-list').innerHTML = statusHTML.join('');
}
//处理日期
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);
  if (delta < 60) {
    return 'now';
  } else if(delta < 120) {
    return '1 minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return '1 hour ago';
  } else if(delta < (24*60*60)) {
    return + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

3. 终端页调用

<script src="http://sheshui.me/twitter/t-json.php?callback=getTwitter&amp;username=你的Twitter用户名&amp;count=20"></script>

—— Updated 2018-10-17 04:30 ——

暂无留言。

非本文主题相关的留言请到:留言本

给我留言 Say something...

* 先[预览],后[提交]。

insert_comment