[英]Using AJAX to access to the Twitter API
我正在考慮在Web應用程序中添加一些twitter功能,因此我開始進行一些測試。 我檢查了調用搜索Twitter URL的方法(有關更多信息,請訪問: http : //dev.twitter.com/doc/get/search ),以獲取包含搜索到的單詞/句子的推文。 我意識到您可以在php中做到這一點,只需使用file_get_contents()
函數獲取搜索URL返回的JSON文件即可。 另外,您也可以直接在JavaScript中創建腳本對象,然后將其附加到正文並使用搜索URL的callback參數來處理數據。
不同的操作方式,但這就是我最終做到的方式:
主要HTML檔案:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
在PHP中獲取JSON數據的位置:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
就是這樣,它可以正常工作。 我調用PHP文件,它返回從搜索URL檢索到的JSON數據,並且在主要的HTML JavaScript函數中,我在div中插入了推文。 問題是,我第一次嘗試使用JavaScript直接執行此操作,並使用Ajax調用搜索URL,如下所示:
主要HTML檔案:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
我以為它應該返回JSON數據,但事實並非如此。 我想知道為什么不這樣做,這就是我想問的。 有人對為什么我無法使用Ajax對象獲取JSON數據有任何想法嗎? 如果搜索URL http://search.twitter.com/search.json?q=%23search_word&rpp=10
返回JSON數據,應該在ajax對象中獲取它,對嗎?
XHR請求通常僅限於相同域的請求; 例如,如果您在bertsbees.com上,則不能使用Ajax方法從twitter.com提取數據。
也就是說,Twitter的API支持一種流行的數據傳輸方法,稱為JSON-P,這實際上只是一種出色的注入技術。 您只需向其傳遞一個回調方法,返回的數據將包裝在所需的函數中,以便對其進行評估和傳遞。
除非您是通過瀏覽器插件執行的,否則無法使用javascript進行跨域請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.