我创建了一个简单的 PHP Twitter 请求,它每 10 分钟缓存一次响应。请求代码如下所示:
$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/user_timeline.json?q=@SolidCAMUK&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 响应时,它似乎充当字符串而不是实际对象......任何人都可以看到任何问题吗?