Estoy estudiando el método php scandir tratando de devolver a javascript el resultado como una matriz. Leí aquí muchas respuestas sobre la búsqueda de Ajax, pero por mi culpa no entendí muy bien cómo pasar los encabezados entre js y php. Desde php (copié el código scandir de https://www.php.net/manual/en/function.scandir.php ) 'echo json_encode ($ arrDir)' devuelve 'content-type = text/html' y en lugar de el contenido de la matriz recibo el código del archivo php como texto. ¿Puede ayudarme a comprender qué hice mal y cómo puedo obtener los valores de la matriz? Si es posible en Vanilla JS. Gracias por adelantado
var arrDir = []; // array with directories to be returned let url = "/testscan.php"; let response = fetch(url) .then(response => { const contentType = response.headers.get('Content-Type'); console.log("result: " + response.status + "\ntype: " + contentType); // iterates all headers and show for (let [key, value] of response.headers) {console.log(`${key} = ${value}`);} if (!response.ok) { // error if(response.status == 404){console.log("file does not exist")} throw new Error(response.status); } if (/text\/html/i.test(contentType)) { return response.text() .then(function(text) { console.log(text); }) } else if (/application\/json/.test(contentType)) { return response.json() .then(function(json) { console.log(json); }) } }) .catch(function (err) { // .catch(error => { // do something when error happens });archivo testscan.php
$dir = "/PRODUCTS"; $arrDir = array(); Scan($dir, $arrDir); echo json_encode($arrDir); function Scan($dir, $arrDir){ // Create array of current directory $files = scandir($dir); if(is_array($files)){ foreach($files as $val){ // Skip home and previous listings if($val == '.' || $val == '..') continue; if(is_dir($dir.'/'.$val)){ $arrDir[$dir][] = $val; Scan($dir.'/'.$val, $arrDir); } else{ $arrDir[$dir][] = $val; }; }; }; return $arrDir; };