Twitter REST API允许开发者通过HTTP请求与Twitter平台交互,获取或操作Twitter数据。JSON是API返回数据的主要格式,具有轻量级、易解析的特点。
AJAX(Asynchronous JavaScript and XML)是一种无需重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。现代AJAX通常使用JSON而非XML作为数据格式。
原因:浏览器同源策略限制
解决方案:
// 使用JSONP或CORS
// 服务器端需要设置响应头
// 或者通过后端代理请求
// 示例:使用fetch API
fetch('https://api.twitter.com/1.1/...', {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
})
.then(response => response.json())
.then(data => console.log(data));
原因:Twitter API v1.1需要OAuth认证
解决方案:
// 需要先获取Bearer Token
const getTweets = async () => {
const response = await fetch('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2', {
headers: {
'Authorization': 'Bearer YOUR_BEARER_TOKEN'
}
});
const data = await response.json();
console.log(data);
};
原因:Twitter API有严格的请求限制
解决方案:
原因:JSON格式不匹配或API响应变化
解决方案:
// 添加错误处理
fetch('https://api.twitter.com/1.1/...')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => {
// 处理数据前先验证结构
if (data && Array.isArray(data)) {
// 处理推文数据
}
})
.catch(error => console.error('Error:', error));
<!DOCTYPE html>
<html>
<head>
<title>Twitter API AJAX示例</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
const btn = document.getElementById('loadTweets');
const tweetsDiv = document.getElementById('tweets');
btn.addEventListener('click', function() {
fetch('/twitter-proxy', { // 通过后端代理解决跨域
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
endpoint: 'statuses/user_timeline',
params: {
screen_name: 'example_user',
count: 5
}
})
})
.then(response => response.json())
.then(tweets => {
tweetsDiv.innerHTML = '';
tweets.forEach(tweet => {
const tweetElement = document.createElement('div');
tweetElement.className = 'tweet';
tweetElement.innerHTML = `
<p><strong>${tweet.user.name}</strong> @${tweet.user.screen_name}</p>
<p>${tweet.text}</p>
<p>${new Date(tweet.created_at).toLocaleString()}</p>
`;
tweetsDiv.appendChild(tweetElement);
});
})
.catch(error => {
console.error('Error:', error);
tweetsDiv.innerHTML = '<p>加载推文失败</p>';
});
});
});
</script>
<style>
.tweet {
border: 1px solid #ddd;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Twitter推文加载示例</h1>
<button id="loadTweets">加载推文</button>
<div id="tweets"></div>
</body>
</html>