用javascript访问Php数组中存储的数据

Accessing data stored in Php array in javascript

本文关键字:存储 数据 数组 javascript 访问 Php      更新时间:2024-01-01

可能重复:
将PHP数组插入Javascript数组

我正在用php读取服务器中的一个文件,并将文件内容存储在一个变量中。现在我想用javascript访问变量,因为我需要用制表符分隔内容,并将内容作为选项添加到Select标记中。

               <?php
                       //read the 'file' content to lines variable
                       $lines = file('file');
                ?>

访问PHP变量的Javascript($lines):

<script type="text/javascript" >
    function readData(){
        var s = '<? echo $lines ?>';
        alert(s);
        }
</script>

只有阵列文本才会弹出警报

我应该怎么做才能在javascript数组变量

中访问$lines数组中存储的数据

file_get_contents('file')而不是file('file')是您的最佳选择。

file函数是使用获取数组中的文件内容,然后逐行迭代(比如foreach)。类似:

foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />'n";
}

可以使用file_get_contents()将文件的内容作为字符串返回。像

$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

如果您在JS中使用内容,则必须注意引号等特殊字符。