我有一个文件夹观察者,我希望每分钟调用一次,但我无法让它工作。
文件夹观察程序将返回1
或0
。如果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);
?>
答案 0 :(得分:5)
只需更改
setTimeout(Update(),timeoutPeriod);
到
setTimeout(Update,timeoutPeriod);
setTimeout
将函数引用作为第一个参数。你不需要setInterval
这里接收&#39; 0&#39;你已经在调用刷新功能了。
答案 1 :(得分:1)
您需要将函数引用传递给setTimeout,还需要使用setInterval(),因为您需要每分钟调用一次
function timedRefresh(timeoutPeriod) {
setInterval(Update,timeoutPeriod);
}
答案 2 :(得分:0)
您需要做的就是将您的功能放在$(document).ready()
内并更改您的超时结构:
<script>
$(document).ready(function(){
setTimeout(function(){
Update()
},timeoutPeriod);
});
</script>
答案 3 :(得分:0)
试试这个
$(document).ready(function(){
setInterval(function(){
//code goes here that will be run every 5 seconds.
$.ajax({
type: "POST",
url: "php_file.php",
success: function(result) {
//alert(result);
}
});
}, 5000);
});