提问人:mini modelli 提问时间:1/28/2022 最后编辑:Markus AOmini modelli 更新时间:1/28/2022 访问量:181
从 js (vanilla) 获取文件 php 并返回数组 (scandir 或 RecursiveIteratorIterator)
Fetch file php from js (vanilla) and return array (scandir or RecursiveIteratorIterator)
问:
从 js (vanilla) 获取文件 php 并返回数组 (scandir 或 RecursiveIteratorIterator)
我尝试获取一个外部 php 文件并将一个数组返回给 javascript。它在本地服务器中运行良好,但在远程服务器中效果不佳,结果始终是:
Error SyntaxError: Unexpected token < in JSON at position 0
如果你给我一个例子来将数据传递给 php 并返回一个数组,我会很高兴。我附上文件index.html和testscan.php,它们不是“最好的”,而只是“我最好的”(我很欣赏任何可以帮助我理解并继续学习JS的答案/解决方案。如果还有其他答案,我深表歉意,我已经阅读了数百本,但我无法解决问题。我要求耐心等待,我今年 75 岁,编程对我来说只是一种爱好,当我年轻的时候,计算机还不存在,现在我的头脑不再很有弹性)
<script>
var j, i;
var arrdir = []; // array with directories to be returned
let pth = "testscan.php"; // file php that executes 'scandir'
let dir = "directory_name"; // directory to be scanned
FetchDirectory(pth,dir)
.then((response) => {
console.log("result: " + response.status + "\ntype: " + response.headers.get('Content-Type'));
if (!response.ok) {
if(response.status == 404){console.log("file does not exist")}
throw new Error(response.status);
}
// return response.text();
// return response.json();
// console.log(response.text());
return response;
})
.then(response => response.json())
.then(arrdir => {
// only to show results
console.log("Total values: " + (arrdir.length) + "\n"); for(i = 0; i < arrdir.length; i++){console.log(i + " - " + arrdir[i] + "\n")};
})
.catch(function (err) {
console.warn('Error ', err);
// console.error(err); // this returns Syntax error in console
});
async function FetchDirectory(pth,dir) {
const response = await fetch(pth, {
method: 'POST',
// headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
// headers: {"Content-Type": "application/json"},
// headers: {"Content-Type": "application/text"},
headers: {"Content-Type": "text/html"},
body: `dir=${dir}`
});
return response.json(); // la stringa JSON restituita viene parsata e convertita in oggetti JavaScript
};
</script>
header('Content-type: text/html');
$dir = $_POST['dir'];
$arrdir = startScan($dir);
echo json_encode($arrdir);
function startScan($dir){
$j = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($j as $index => $value) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $value);
if((!($value == '.') && !str_contains($value, '._') && !str_contains($value, '..') && !str_contains($value, '.DS_Store'))){
$value = str_replace(DIRECTORY_SEPARATOR,"/",$value);
if (is_dir($value)) { // it is a folder
if(substr($value, -1) == '.'){$value = substr($value, 0, -1);}; // delete last dot from folders
$value = substr($value, 0, -1); // delete last '/' from folders
if($index > 0){
$arrdir[] = $value;
};
}
else{ // it is a file
$arrdir[] = $value;
};
};
};
return $arrdir;
};
答: 暂无答案
评论
testscan.php?dir=test_dir
.then((response) => {
console.log(response);