javascript - Ajax 每分钟调用一次

标签 javascript php ajax

我有一个文件夹观察器,我想每分钟调用一次,但我无法让它工作。

文件夹观察器将返回 10。如果 data == 1 则页面将被刷新,如果 0 等待一分钟并再次运行。

谁能帮我找出问题所在?

脚本:

     <script type="text/javascript"> 
function timedRefresh(timeoutPeriod) {
setTimeout(Update(),timeoutPeriod);
}

function Update() {
            $.ajax({
            url: "checkfolder.php", 
            type: "POST",


            success: function (data) {

                if(data == "1"){
                   //Page will be updated
                }
                else{
                    timedRefresh(60000);
                }

            }
        });

        }

</script>

继承人 checkfolder.php:

    <?php
// Configuration ///////////////////////////////////////////////////////////////
$host ='xxxx';
$port = 21;
$user = 'xxxx';
$pass = 'xxxx';
$remote_dir = '../img/uploads/';
$cache_file = 'ftp_cache';

// Main Run Program ////////////////////////////////////////////////////////////

// Connect to FTP Host
$conn = ftp_connect($host, $port) or die("Could not connect to {$host}\n");

// Login
if(ftp_login($conn, $user, $pass)) {

  // Retrieve File List
  $files = ftp_nlist($conn, $remote_dir);

  // Filter out . and .. listings
  $ftpFiles = array();
  foreach($files as $file)
  {
    $thisFile = basename($file);
    if($thisFile != '.' && $thisFile != '..') {
      $ftpFiles[] = $thisFile;
    }
  }

  // Retrieve the current listing from the cache file
  $currentFiles = array();
  if(file_exists($cache_file))
  {
    // Read contents of file
    $handle = fopen($cache_file, "r");
    if($handle)
    {
      $contents = fread($handle, filesize($cache_file));
      fclose($handle);

      // Unserialize the contents
      $currentFiles = unserialize($contents);
    }
  }

  // Sort arrays before comparison
  sort($currentFiles, SORT_STRING);
  sort($ftpFiles, SORT_STRING);

  // Perform an array diff to see if there are changes
  $diff = array_diff($ftpFiles, $currentFiles);
  if(count($diff) > 0)
  {
    echo "1";//New file/deleted file
  }
  else{
   echo "0";//nothing new
}

  // Write new file list out to cache
  $handle = fopen($cache_file, "w");
  fwrite($handle, serialize($ftpFiles));
  fflush($handle);
  fclose($handle);
}
else {
  echo "Could not login to {$host}\n";
}

// Close Connection
ftp_close($conn);
?>

最佳答案

只是改变

setTimeout(Update(),timeoutPeriod);

setTimeout(更新,timeoutPeriod);

setTimeout 在传递函数调用时将函数引用作为第一个参数。您不需要此处的 setInterval,因为在收到“0”时您已经在调用刷新函数。

关于javascript - Ajax 每分钟调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764767/

相关文章:

javascript - 直接修改state然后调用setState是不是更快?

php - Ajax 读取 PHP

php - 如何从 DOMNodeList 获取原始数据

javascript - node.js 和单页 Web 应用程序

javascript - 隐藏与 css vs JS 创建元素 vs ajax

javascript - 解析 - 无法从安装类中获取和更新列

javascript - 为什么javascript函数每次都会运行?

javascript - 是否可以在 ngRepeat 中重命名项目

php - HTML 显示表中数组的数据

php - 如何从自动完成中获取单击的输入单选值以将表单发送到 php 文件