将php数组存储在javascript数组中

时间:2016-06-09 03:12:57

标签: javascript php arrays

这是我的php代码,它获取dir中的文件列表并将其存储在数组$files中:(注意我尝试在小提琴here中运行它但不确定我是否能够用这个例子)

<?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>";
?>

之后是我的javascript,我想在我的javascript变量中存储php数组,但是我在控制台中收到此错误Uncaught SyntaxError: Unexpected token ILLEGAL任何人都能以我的方式纠正错误吗?

<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 尝试jsfiles = "<?php json_encode($files);?>";,但没有错误,但数组中的值未显示在console.log("the files are:",jsfiles);

EDIT3 - 让它运转

我的代码片段。我不得不删除下面的两行,即使我已被注释掉了。不确定为什么

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

2 个答案:

答案 0 :(得分:4)

将PHP输出到javascript时始终始终使用json_encode

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

即使这只是一个数字或简单的字符串,json_encode也可以保护您免受意外,并确保它是有效的javascript对象表示法。

答案 1 :(得分:-1)

您需要确保输出采用纯JSON格式,以便您的javascript可以轻松解析它以使用它。

你需要转换为json:因为jszobody建议你可以使用json_encode();要做到这一点,但你还需要设置标题...

name:phil OR name:tom

通过这种方式,javascript可以轻松地将输出解析为javascript json对象,并且您将能够轻松地使用它...

最后一个生产阶段还有一个小费,也就是......

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

因此只有纯JSON输出转到javascript