简体   繁体   中英

storing a php array in a javascript array

This is my php code that gets a list of files in a dir and stores it in the array $files : (Note I tried running this in a fiddle here but not sure if I am able with this example)

<?php

echo "<hr>";
echo "<hr>";


$files = array_slice(scandir('/path/to/dir'), 2); // this gets a list of all files in the dir

//
echo "this is the array: <br>";
print_r($files); // this prints the array 
echo "<br>";
echo "<br>";

echo "this is each element in the array: <br>";
foreach ($files as &$value) {
    print_r($value."<br>"); // this prints each element of the array 
}

echo "<hr>";
echo "<hr>";
?>

Immediately after that is my javascript where I want to store the php array in my javascript variable, but I get this error Uncaught SyntaxError: Unexpected token ILLEGAL in the console. Can anyone correnct the erro in my ways?

<script>
// then echo it into the js/html stream
// and assign to a js variable
var jsfiles =[];
jsfiles = "<?php print_r($files);?>";

// then
alert(jsfiles);
console.log("the files are:",jsfiles);

</script>

EDIT2 tried jsfiles = "<?php json_encode($files);?>"; which gives me no error but values in array are not displayed in console.log("the files are:",jsfiles);


EDIT3 - got it working

snippet of my code. I had to delete the 2 lines below, even though I though they were commented out. Not sure why

<script>
// then echo it into the js/html stream
// and assign to a js variable
//var jsfiles =[];
//jsfiles = "<?php print_r($files);?>";   ------ had to delete this line
//jsfiles = <?php json_encode($files) ?>; ------ had to delete this line
var jsfiles = <?php echo json_encode($files) ?>;

Always always always use json_encode when outputting PHP to javascript.

var jsfiles = <?php echo json_encode($files) ?>;

Even if this were just a number or simple string, json_encode protects you from surprises and ensures it will be valid javascript object notation.

You need to make sure that your output is in pure JSON format so that your javascript can easily parse it to use it.

You need to convert is to json: as jszobody suggested you can use json_encode(); to do that, but you are also required to set headers by...

header('Content-type:application/json;');

By this way javascript will easily parse the output to an javascript json object and you will be able to use it easily...

One more tip in final production stage, also put..

error_reporting(0); 

So only pure JSON output goes to javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM