仅在更改csv行计数时刷新页面

时间:2012-09-28 14:24:43

标签: php javascript ajax csv

从我所做的研究中我认为我可能不得不使用Ajax,但我并不熟悉它而且我似乎无法找到适合我的功能的答案。

我没有使用数据库(也许我应该但我正在寻找一个短期修复)。我正在使用一个csv文件,用户的数据输入到PHP。

我的php循环遍历csv文件并显示包含内容的表。它只是一列推特用户名。

<php?    
echo "<table>\n";
$file = file("Twitter.csv");
$file = array_reverse($file);
foreach($file as $f){
$string=$f; 
$string=str_replace("\r\n","",$string);
    echo "<tr>\n";
            echo "<td><a href='http://twitter.com/".$string."' target='_blank'><img src='https://api.twitter.com/1/users/profile_image?screen_name=".$string."&size=bigger' border='0'></td>\n<td>\n<a href='https://twitter.com/".$string."' class='twitter-follow-button' data-show-count='false' data-lang='en' data-size='large'>Follow @".$string."</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src='//platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');</script>";
    echo "</td>\n</tr>\n";
    }
echo "\n</table>";
?>

一旦用户授权推特应用程序并获得他们的用户名,他们就会被重定向到列出其他名称的页面。但是,我希望在csv文件的linecount更改时更新该页面。

我需要能够每隔x秒运行一次脚本以获取行数,并且是否已更改为刷新。

我认为逻辑很简单:

$linecount = count(file('Twitter.csv'));
every x seconds{
    $checkcount = count(file('Twitter.csv'));
    if ($checkcount != $linecount){
     refresh page
    }
 }

我觉得逻辑是正确的 - 我没有足够的知识来弄清楚如何编写代码来工作。

如果文件没有更新,页面将不会刷新,但代码仍会每隔x秒执行一次,直到文件发生变化。

1 个答案:

答案 0 :(得分:2)

解决方案可以分几步完成(未经测试):

  • 您的PHP脚本将filemtime('Twitter.csv')的当前值写入JavaScript块:
echo '<script>var currentTS = ', (int)filemtime('Twitter.csv'), ';</script>';
  • 创建一个小型PHP脚本,返回修改时间Twitter.csv
echo json_encode(array('ts' => filemtime('Twitter.csv')));
  • 编写一个JavaScript函数,使用一些简单的jQuery通过AJAX获取时间戳:
function myFunction() {
    $.ajax({
      url: '/path/to/check_mod_time.php',
      timeout: 2000, // don't wait too long
      success: function(data) {
        if (currentTS < data.ts) {
            location.reload();
        }
    });
}
  • 使用setInterval()
  • 让您的函数每X秒调用一次
setInterval(myFunction, 5000) // run every 5 seconds