Javascript 如何在HTML中调用TwitterAPI函数并显示结果?
我有一个工作功能,当在app.js文件中使用时,它将成功打开一个twitter流,并显示以下内容:如果使用console.log而不是打印。但是,当我获取函数并将其放入index.html内的脚本中时,我得到了错误referenceError:require not defined我还得到了其他脚本的get错误..也许我没有正确地引用它们,但我尝试只使用一个脚本包含它们 我正试着自己去学习这一切。我以前做过一个简单的静态网站,但只使用html、css和一些基本的jquery。我希望能够通过css对函数输出的文本进行样式化Javascript 如何在HTML中调用TwitterAPI函数并显示结果?,javascript,html,rest,twitter,Javascript,Html,Rest,Twitter,我有一个工作功能,当在app.js文件中使用时,它将成功打开一个twitter流,并显示以下内容:如果使用console.log而不是打印。但是,当我获取函数并将其放入index.html内的脚本中时,我得到了错误referenceError:require not defined我还得到了其他脚本的get错误..也许我没有正确地引用它们,但我尝试只使用一个脚本包含它们 我正试着自己去学习这一切。我以前做过一个简单的静态网站,但只使用html、css和一些基本的jquery。我希望能够通过css
<!DOCTYPE html>
<html>
<head>
<title>Streaming</title>
<script src="..Twitter/config.js"></script>
<script src="..Twitter/package.json"></script>
<script src="..Twitter/app.js"></script>
<script type = "text/javascript">
function displayStream() {
var Twit = require('twit');
var T = new Twit(config);
var stream = T.stream('statuses/filter', { track: 'Bernie Sanders' });
var count = 0;
var totalSentiment = 0;
stream.on('tweet', function (tweet) {
//Exclude retweets
if(tweet.text.startsWith("RT") === false) {
print(tweet.text)
print("Sentiment score: " + sentiment(tweet.text).score)
count += 1;
totalSentiment += sentiment(tweet.text).score;
print(count + " tweets analyzed");
print("Aggregate Sentiment: " + totalSentiment);
print("Average Sentiment:" + (totalSentiment/count).toFixed(2) + "\n");
};
});
};
使用Ajax脚本,您可以通过以下方式请求URL并获得响应
使用普通Jquery,您可以通过使用Jquery加载函数实现相同的结果
使用纯javascript,您可以使用XMLHttpRequest实现
只需使用javascipt即可。它将提供与AJAX相同的感觉 例如:
fetch('ApiToFetchTweets', {
method: 'get'
})
.then(function(response) {
console.log('response here: ',response);
}).then(function(json) {
//console.log('parsed json', json);
}).catch(function(ex) {
//console.log('parsing failed', ex);
})
谢谢
Dinesh我很愿意,但对于这个项目,我不应该使用jQuery。只需简单的JavaScript除非还包括框架/库的另一个标记,否则需要一个纯JavaScript的答案。虽然这个代码片段可以解决这个问题,但确实有助于提高您的文章质量。请记住,您将在将来回答读者的问题,而这些人可能不知道您的代码建议的原因。-我需要在哪里插入代码?我不知道如何集成它们…Twitter/config.js不是一个有效的路径,应该是../Twitter/config.js。你能把它和我的代码放在一起吗?我不知道如何将您的代码与我的代码集成。请确认您使用哪种服务器端语言来获取twitter提要?因此,我可以根据您的要求更新我的答案。NodeJs并使用twit包进行快速更新
$.ajax({
url: 'url',
})
.done(function(data) {
document.getElementById("#myResponse").innerHTML=data;
})
.fail(function() {
alert("Ajax failed to fetch data")
})
$( "#div").load( "url", function( response, status, xhr ) {
console.log(response.ok);
document.getElementById("#myResponse").innerHTML=response;
if ( status == "error" ) {
}
});
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'url', true);
xhr.send(null);
fetch('ApiToFetchTweets', {
method: 'get'
})
.then(function(response) {
console.log('response here: ',response);
}).then(function(json) {
//console.log('parsed json', json);
}).catch(function(ex) {
//console.log('parsing failed', ex);
})