2013-04-12 39 views
0

我創建了一個簡單的PHP Twitter請求,每10分鐘緩存一次響應。請求代碼如下:使用JSONP的PHP Twitter請求

$twitter_result = false; 

if (file_exists('twitter.json')) { 
    $data = json_decode(file_get_contents('twitter.json')); 
    if ($data->timestamp > (time() - 10 * 60)) { 
     $twitter_result = $data->twitter_result; 
    } 
} 

if (!$twitter_result) { 
    $twitter_result = file_get_contents('http://api.twitter.com/1/statuses/[email protected]&rpp=1&screen_name=SolidCAMUK&count=1'); 
    $data = array ('twitter_result' => $twitter_result, 'timestamp' => time()); 
    if(file_put_contents('twitter.json', json_encode($data))) { 
     //echo 'success'; 
    } else { 
     //echo 'error'; 
    } 
} 

$file = file_get_contents('twitter.json'); 

header("content-type:application/json"); 
if($_GET['callback']) { 
    echo $_GET['callback'] . '(' . $file . ')'; 
} else { 
    echo $file; 
} 
exit; 

而且這個頁面的返回JSONP的例子是這樣的:http://dev.driz.co.uk/phptwitter/?callback=Test

然後我想在我的測試場景在這裏使用JSONP:http://dev.driz.co.uk/phptwitter/test.php

但是數據沒有正確顯示。我猜JSON格式不正確,因爲當我console.log響應,它似乎是作爲一個字符串,而不是一個實際的對象...任何人都可以看到任何問題?

回答

1

返回的JSON格式沒有任何問題。這是有效的,你可以檢查它here

您正在做console.log(response.twitter_result);,這就是爲什麼你看到純文本。 如果你做console.log(response);你會看到實際返回的對象。

response.twitter_result是一個對象,也不過你得先分析它這樣

success: function(response){ 
       var twitter_result = $.parseJSON(response.twitter_result); 

       console.log(twitter_result[0].text); 
       //and here you can apply your parseTwitterText() function as you wish 
} 
+0

感謝朋友。這解決了它。 – Cameron