1

I want to pass a php array to javascript. I've tried several examples taken form this site, but the rest of my code seem not to recognize them. I think the problem is in the quotes or format of the array.

First: var functionlist defined as below works OK.

<script type="text/javascript">
    var functionlist = Array('1','2','3','4','5','6','7','8','9','10','11','12');
    //Rest of the code
</script>

Second: var functionlist defined as below works OK.

<script type="text/javascript">
    var functionlist=Array("1","2","3","4","5","6","7","8","9","10","11","12");
    //Rest of the code
</script>

But the code below is not working, despite the fact that echoing $TransfArray renders something quite similar to the above.

<?php
    for ($i = 0; $i <= 12; $i++) {
        $OriginalArray[$i] = $i;
    }
    $TransfArray= "'" . implode("','", $OriginalArray) . "'";
?>

<script type="text/javascript">
    var functionlist = Array(<? echo $TransfArray; ?>);
    //Rest of the code
</script>

Nor does the code below

<?php
    for ($i = 0; $i <= 12; $i++) {
        $OriginalArray[$i] = $i;
    }
    $Original_to_json = json_encode($OriginalArray);
?>

<script type="text/javascript">
    var functionlist =  <?php echo $Original_to_json; ?>;
    //Rest of the code
</script>

Does anyone detect the problem? Thnaks in advance.

4

3 回答 3

2

使用铸造如下,

<?php
for ($i = 0; $i <= 12; $i++) {
$OriginalArray[]= (String)$i;
}
$Original_to_json=json_encode($OriginalArray);
?>

<script type="text/javascript">
var functionlist =  <?php echo $Original_to_json; ?>;
//Rest of the code
</script>
于 2013-02-26T13:26:36.487 回答
0

用 PHP 编写 JavaScript 代码是一种糟糕的做法。你不应该那样做。相反,您可以做一些不同且简单的事情。

  1. 在 PHP 中,您通过将数组转换为 JSON 对象来生成 JSON 文档。为此使用 json_encode 函数。将您的文件命名为“json.php”(尽管命名为 data.json 可能是一种更好的做法,但您必须执行更多步骤)。
  2. 现在,您可以在 HTML 文档中包含该文件, <script src="json.php"></script>或者您可以使用 AJAX 动态加载它。
  3. JSON 对象将具有 JavaScript 数组。
于 2013-02-26T13:24:44.707 回答
-1

尝试这个 :

<script type="text/javascript">
var functionlist =  <?php echo json_encode($OriginalArray); ?>;
//Rest of the code
</script>

享受 ;)

于 2013-02-26T13:24:36.303 回答