繁体   English   中英

将php数组存储在javascript数组中

[英]storing a php array in a javascript array

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

<?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控制台中的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) ?>;

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

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

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

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

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

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

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

在最后的生产阶段还有一个小费,也放了......

error_reporting(0); 

所以只有纯JSON输出转到javascript

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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