我一直试图找到在后台运行长PHP脚本并间歇性地获取响应的最佳方法。我认为我能找到的最佳解决方案是将EventSource
与javascript一起使用。我松散地遵循了此tutorial,但是在将按钮文本更改为“扫描”后,我的代码无法进入我指定的功能,因为我在控制台日志中看不到任何东西,所以我知道这一点……我只是在使用简单的测试代码,并向其传递一个变量,然后尝试在php脚本中进行检索,然后创建一个数组并传递回客户端,并在<span>
这是我的基本代码(我认为):
Javascript:
function startLibScan(){
var scan_sse = new EventSource('ajax/test.php?media_dir='+ media_dir);
scan_sse.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
console.log(result.msg);
if(result.code == '200') {
console.log('Received');
scan_sse.close();
document.getElementById("scan_library_response").innerHTML = result.msg;
document.getElementById("scan_library_submit").innerHTML='<i class="fas fa-check"></i> Complete!';
} else {
scan_sse.close();
console.log('ERROR');
}
});
}
$("#scan_library_submit").on('click', function(e){
var media_dir = $("#media_dir").val();
var media_ext = document.forms['scan_library_form'].elements[ 'media_ext[]' ];
if( media_dir =='' || media_ext == '' )
{
document.getElementById("scan_library_response").innerHTML = '<font color="red"><i class="fas fa-times"></i> All Fields Required.</font>';
return
}
this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Scanning...';
startLibScan();
});
ajax / test.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$media_dir = $_GET['media_dir'];
//$media_ext = $_GET['media_ext'];
//$media_ext = json_encode($media_ext, TRUE);
$msg = "Media directory: $media_dir";
$response = array(
'code' => '200',
'msg' => $msg
);
echo "data: ". json_encode($response).PHP_EOL;
?>