如何在捕获新请求时检查JSON对象值是否已更改


How to check if a JSON object value has changed when new request is captured

我有一个php脚本,以JSON格式获取特定用户的最新tweet。JSON被解析为一个AJAX函数,该函数在页面上以一个ID显示最新的tweet。每隔x秒设置一个计时器来执行上述操作,检索最新的tweet,而无需用户刷新页面。这是完美的。

我现在正在尝试创建一个通知功能,当有一个新的tweet显示通知。在检索到的JSON中,每条tweet都有一个名为"id_string"的唯一ID。我想做的是以某种方式存储生成的id_string的值,然后每次请求检索新的tweet时,检查新的'id_string'对存储的一个,如果它是不同的,然后显示通知。

有什么好主意吗?我已经研究过本地存储,但我不是很熟悉这个,据我所知,你不能在本地存储中检查字符串与其他字符串。

下面是帮助解释我的问题的必要代码:

PHP向twitter发出请求并生成JSON格式的输出(tweets.php):

require_once('config/FrameFunctions.php');
$output = array();
foreach ($tweeters as $i => $tweeter){
    $theTweeter = new Tweeter($tweeter, $tmhOAuth);
    $allinfo = $theTweeter->getTweets();
    $output[$i] = $allinfo;
}
header("Content-type: application/json");
echo json_encode($output);

每x秒发出一次请求并生成客户端输出的javascript:

$(document).ready(function() {
   $('.fancybox').fancybox();
   /*
   *  call ajax function and update latest
   */        
    var refreshTweets = function() {
      console.log("updating..");
      $.ajax({url:"tweets.php",success:function(result){
        tweets = eval(result);
        for(i=0;i<tweets.length;i++){
            $("#latesttweet"+(i+1)).html(
               tweets[i][0].user.name + ": " + tweets[i][0].text
             );  
        }
      }});
    }
    refreshTweets();
    //set the time in milliseconds here for each refresh
    setInterval(refreshTweets , 30000); //Interval
});

这是一个基于我上面评论的解决方案

/*
NOTE : allTweets will have to be populated with all the tweets ids on the page prior           
to being called in refreshTweets so that it does not trigger fake notifications
*/
    var allTweets = Array();
    $(document).ready(function() {
        $('.fancybox').fancybox();
        /*
         *  call ajax function and update latest
         */        
        var refreshTweets = function() {
            console.log("updating..");
            $.ajax({url:"tweets.php",success:function(result){
                    tweets = result;
                    for(i=0;i<tweets.length;i++) {
                        //check if its a new tweet or not
                        if (allTweets[tweets[i][0].id_string] === undefined) {
                            allTweets[tweets[i][0].id_string] = 1;    
                            //trigger notification here!
                        }
                        $("#latesttweet"+(i+1)).html(
                        tweets[i][0].user.name + ": " + tweets[i][0].text
                    );  
                    }
                }});
        }
        refreshTweets();
        //set the time in milliseconds here for each refresh
        setInterval(refreshTweets , 30000); //Interval
    });

我想和其他人一起评论,但是我想我太新了。

无论如何,如果你不存储敏感信息,你可以将数据存储在JSON中,PHP可以快速写入和读取较小的文件。如果你要存储大量的数据,你可能想要查看保存值到MySQL数据库或类似的东西。

设置JSON存储和MySQL数据库似乎在这里有很好的文档