如何获得C中所有文件的文件名列表:xampphtdocsdumpuploads in php变量它们获得php变量在js中的值
服务器端阅读文件
$files = [];
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$files[] = $entry;
}
}
closedir($handle);
}
渲染页面并在script标签中返回$文件。像下图:
<script type="text/javascript">
const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>);
console.log('myFiles', files);
</script>
将一个变量从PHP传递给JS首先你需要知道PHP是在服务器端呈现的;然而JS是在客户端执行的;将变量从PHP发送到JS的一种方式是使用JSON
<!-- In your file of PHP you have: -->
<!-- some code of php to generate variable of all your files... -->
<?php $files = ['dir1','file1.txt','img.jpg']; ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- here inside the same file you have your script js -->
<script type="text/javascript">
// call your variable with format JSON
var filesJSON = <?php echo "'".json_encode($files)."'"; ?>;
console.log(JSON.parse(filesJSON)); //['dir1', 'file1.txt', 'img.jpg']
</script>
</body>
</html>