dream518518518 2013-04-12 09:37
浏览 29
已采纳

使用JSONP的PHP Twitter请求

I have created a simple PHP Twitter request that caches the response every 10 minutes. The request code looks like:

$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;

And an example of the returned JSONP for this page looks like: http://dev.driz.co.uk/phptwitter/?callback=Test

And then I'm trying to use this JSONP in my test scenario here: http://dev.driz.co.uk/phptwitter/test.php

However the data isn't being displayed properly. I'm guessing that the JSON isn't formatted correctly, as when I console.log the response, it seems to be acting as a string rather than an actual object... Can anyone see any issues?

  • 写回答

1条回答 默认 最新

  • doulianqi3870 2013-04-12 09:50
    关注

    There is nothing wrong with the returned JSON format. It is valid and you can check it here.

    You are doing console.log(response.twitter_result); and that's why you see plain text. If you do console.log(response); you will see the actual returned object.

    The response.twitter_result is an object also but you have to parse it first like this

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考