我正在考虑在我的网络应用程序中添加一些推特功能,所以我开始做一些测试。我检查了调用搜索Twitter URL的方式(更多信息:http://dev.twitter.com/doc/get/search),以获取包含搜索的单词/句子的推文。我意识到你可以在php中只使用file_get_contents()
函数获取搜索URL返回的JSON文件。您也可以直接在JavaScript中创建脚本对象,将其附加到正文并使用搜索URL的回调参数来处理数据。
不同的方法,但这是我最终做到的方式:
主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数据吗?如果搜索网址http://search.twitter.com/search.json?q=%23search_word&rpp=10
返回JSON数据,则应该在ajax对象中获取,对吧?
答案 0 :(得分:1)
XHR请求通常仅限于同域请求;例如,如果您在bertsbees.com上,则无法使用Ajax方法从twitter.com提取数据。
也就是说,Twitter的API支持一种流行的数据传输方法JSON-P,它实际上只是一种美化的注入技术。你只需传递一个回调方法,返回的数据将被包装在你想要的函数中,因此它被eval'd并传入。
答案 1 :(得分:0)
除非您使用浏览器插件,否则无法使用javascript创建跨域请求。