2011-02-07 139 views
0

我正在考慮在我的Web應用程序中添加一些Twitter功能,所以我開始做一些測試。我檢查了調用搜索推文鏈接的方式(更多信息在:http://dev.twitter.com/doc/get/search),以便獲取包含搜索到的單詞/句子的推文。我意識到你可以在php中做到這一點,只需獲取搜索URL返回的JSON文件file_get_contents()函數。您也可以直接在JavaScript中創建腳本對象,將其附加到主體並使用搜索URL的回調參數來處理數據。使用AJAX訪問Twitter API

不同的方法可以做到,但這就是我終於做到了方式:


主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搜索網址,例如:

主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對象中獲得,對吧?

回答

0

您無法使用javascript進行跨域請求,除非您使用瀏覽器插件。

+0

更多關於http://en.wikipedia.org/wiki/Same_origin_policy – BrunoLM 2011-02-07 09:30:13

+0

謝謝BrunoLM! – Daniel 2011-02-08 02:01:27

1

XHR請求通常限於同域請求;例如,如果您使用的是bertsbees.com,則無法使用Ajax方法從twitter.com提取數據。

也就是說,Twitter的API支持一種流行的數據傳輸方法,稱爲JSON-P,它實際上只是一種榮耀的注入技術。您只需將它傳遞給一個回調方法,並且返回的數據將被包裝在您所需的函數中,以便它被評估並傳入。