有没有办法使用 JavaScript 定期运行 php 脚本?
我已经在 JavaScript 中尝试了几种事件和计时,但我仍然不满意。
我创建了一个 php 文件来从 url 检索 json 文件。
现在我想在用户在输入中设置的每个间隔时间运行我的 php 文件。
我的表单具有以下属性:
uri
开始
完成
间隔
这是我的 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(),
关于javascript - 使用javascript以间隔时间定期运行php脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28067364/