使用 JavaScript 定期运行 PHP 脚本,间隔时间


run php script periodically with interval time using javascript

有没有使用JavaScript定期运行php脚本?
我已经在 JavaScript 中尝试了几个事件和时间,但我仍然不满意。
我创建了一个 php 文件来从 url 中检索 json 文件。
现在我想在用户输入中设置的每个间隔时间运行我的 php 文件。

我的表单具有以下优点:


乌里开始
完成
间隔

这是我的 php 代码:

function toCsv(){
    //Date Format
    $date=date("M-d-Y, 'a''t g.i a", time());
    //URI API Endpoint
    //$uri="https://data.cityofchicago.org/resource/t2qc-9pjd.json";
    $uri= $_POST['input_uri'];
    //Time interval
    $interval= $_POST['set_timer'];
    //Named File
    $file_name= $_POST['file_name'];
    //Get File JSON
    $json=file_get_contents($uri);
    $filecsv = fopen("dataset/csv/dataset-".$file_name."-".$date.".csv", "w") or die("Unable to open file!");
    $array = json_decode($json, true);
    $firstLineKeys = false;
    foreach ($array as $line)
    {
        if (empty($firstLineKeys))
        {
            $firstLineKeys = array_keys($line);
            fputcsv($filecsv, $firstLineKeys);
            $firstLineKeys = array_flip($firstLineKeys);
        }
        fputcsv($filecsv, array_merge($firstLineKeys, $line));
    }    
}

只需使用 setInterval 并运行一个 ajax 请求(示例中每 5 秒一次)

setInterval(function(){
   $.post('1.php?', {input_uri:"value", set_timer:"value", file_name:"value"}, 
    function(data){            
      //do something with the information returned from the php file
    }, 'html')
   }, 5000);

您应该将"value"替换为输入字段的实际值(如input_uri:$("#input_uri").val(),

呢...

function getJSON(){
    setTimeout(function(){ 
        $.post( "YOUR PHP FILE NAME", {input_uri : "//form data", file_name : "//form data" } )
        .done(function( data ) {
            alert("php function ran");
        });
        getJSON();
    }, 3000); // Edit this timing here to set the interval (milliseconds)
}

在你的PHP文件中,你只需要确保你在底部运行你的函数......

        fputcsv($filecsv, array_merge($firstLineKeys, $line));
    }    
}
toCsv();

希望这有帮助!

另一种简单的方法是在您的主页上执行此操作:

<iframe src="csv_file.php?input_uri=value[...]" style="display:none;"></iframe>

在您的csv_file.php末尾添加此行:

<meta http-equiv="refresh" content="5">

5刷新的秒数。

此方法不需要任何 javascript,适用于大多数 Web 浏览器(纯文本浏览器和禁用 iframe 的浏览器除外)。


如果用户需要编辑值,可以发送表单(以任何发送方式)并添加参数。

为简单起见,可以称之为 refresh .
使用参数的示例:

您可以在主页中使用它:

<iframe src="csv_file.php?input_uri=value[...]&refresh=5" style="display:none;"></iframe>

csv_file.php 上,您可以使用以下内容:

<meta http-equiv="refresh" content="<?php echo isset($_REQUEST['refresh']) && ($_REQUEST['refresh']=(int)$_REQUEST['refresh'])?$_REQUEST['refresh']:'5'; ?>">