简体   繁体   English

将数组从PHP传递到Javascript

[英]Passing an Array from PHP to Javascript

I'm trying to pass on a PHP array to then use the array in JavaScript. 我试图传递一个PHP数组,然后在JavaScript中使用该数组。

The PHP code I'm using is as follows: 我正在使用的PHP代码如下:

<?php

$link = mysqli_connect("localhost", "root", "password", "database");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $query = "SELECT * FROM Employees";

    if ($result = mysqli_query($link, $query)) {

        /* fetch associative array */
        while ($row = mysqli_fetch_assoc($result)) {

            $data[] = $row;
        }
        print_r($row);
        /* free result set */
        mysqli_free_result($result);
    }
    /* close connection */
    mysqli_close($link);

//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($data);
?>

JavaScript: JavaScript:

<script> 
    var array = <?php echo $data; ?>; 
    console.log(array); 
</script>

The data array in PHP doesn't seem to get passed on to the Javascript var array . PHP中的data array似乎没有传递给Javascript var array When looking at the console on firebug the following error messages are displayed: 在Firebug上查看控制台时,显示以下错误消息:

Notice - Array to string conversion. 注意-数组到字符串的转换。

I'd really appreciate any help as to why this error is occurring. 我非常感谢您提供任何有关为什么会发生此错误的帮助。

Maybe because you are echo'ing the array instead of the json encoded string. 可能是因为您正在回显数组而不是json编码的字符串。

Use this 用这个

<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>

I believe it should be: 我认为应该是:

<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>

You're using json_encode in $data but you're not using that variable in your code. 您在$ data中使用json_encode,但未在代码中使用该变量。 Could that be it? 可以吗?

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

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