[英]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);
我的代碼片段。 我不得不刪除下面的兩行,即使我已被注釋掉了。 不知道為什么
<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.