我如何在 php 變數中獲取 C:\xampp\htdocs\dump\uploads 中檔案的所有檔案名的串列,它們在 js 中獲取 php 變數的值
uj5u.com熱心網友回復:
要將變數從 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>
uj5u.com熱心網友回復:
服務器端 讀取檔案。
$files = [];
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$files[] = $entry;
}
}
closedir($handle);
}
渲染頁面并在腳本標記中回顯 $files。像下面這樣:
<script type="text/javascript">
const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>);
console.log('myFiles', files);
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339347.html
標籤:javascript php html
