2012-01-04 23 views
1

有了以下代碼,最新的推文只是偶爾在Chrome中顯示,但始終在Firefox中顯示。通常只會在Chrome中顯示/?在網址上,但刷新時消失。最新推文不總是顯示

jQuery(document).ready(function(){ 
console.log("getting twitter data.."); 
jQuery.getJSON("http://twitter.com/statuses/user_timeline/*hidden*.json?callback=?", function(data) { 
    console.log("got it..", data); 
     jQuery("#tweet").html(data[0].text); 
     jQuery("#ttime").html(data[0].created_at); 
}); 
}); 

回答

0

您正試圖從twitter API獲取直接的JSON。這是不可能的,因爲same origin policy。您只能從自己的域中獲取JSON。

解決方法存在,它被稱爲JSONP(帶填充的JSON),這就是Twitter正在使用的。您需要將函數的名稱追加到URL中的callback參數中。這個函數然後在twitter API加載時執行。

例如,你可以做這樣的:

的JavaScript

function render(data) { 
    // data is the object that contains your twitter data. It's an usual JavaScript object. 
} 

HTML

<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/username? 
callback=render"></script> 

確保render已經加載時,Twitter的API負載。