Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
Ajax fetch external file php and return array to javascript

I am studying the php scandir method trying to return to javascript the result as an array. I read here many answers about Ajax fetch but because of my fault I didn't quite understand how to pass the headers between js and php. From php (I copied the scandir code from https://www.php.net/manual/en/function.scandir.php) 'echo json_encode ($ arrDir)' returns 'content-type = text / html' and instead of the array contents I receive the php file code as text. Can you please help me to understand what I did wrong and how can I get the array values? If possible in Vanilla JS. Thanks in advance

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
});

file 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;
};
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda