简体   繁体   中英

json_encode doesn't work from php array to js array

I want to transform a php array into a javascript array.

When I try this code:

<?php
//db data
$verbindung = new mysqli($host_name, $user_name , $password, $database);

if ($mysqli->error) {
    die('Verbindung schlug fehl:');
}
$sql= "SELECT Name FROM Zutaten;";
$result = mysqli_query($verbindung, $sql);
$zutatName = array();

while($row = $result->fetch_array(MYSQLI_ASSOC)){
    $zutatName[] = $row['Name'];
}    
print_r(array_values($zutatName));

?>
<script>
var zutatenArray = <?php echo json_encode($zutatName); ?>;
</script>

I get the following error messeage: "SyntaxError: expected expression, got ';' var zutatenArray = ;"

When I use this code:

 <?php
    //db data
    $verbindung = new mysqli($host_name, $user_name , $password, $database);

    if ($mysqli->error) {
        die('Verbindung schlug fehl:');
    }
    $sql= "SELECT Name FROM Zutaten;";
    $result = mysqli_query($verbindung, $sql);
    $zutatName = array();

    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $zutatName[] = $row['Name'];
    }    
    print_r(array_values($zutatName));

    ?>
    <script>
    var zutatenArray = [<?php echo json_encode($zutatName); ?>];
    </script>

Then there is an empty javascript array. What am I missing?

Best regardds

Your array braces are unecessary:

var zutatenArray = [<?php echo json_encode($zutatName); ?>];
                   ^--------------------------------------^

as they would be added already by json_encode() . Given that your error message says zutatenArray = ; , your posted code is NOT what is producing this error.

Even if json_encode() failed utterly and returned a boolean false, the generated Javascript would've looked like

var zutatenArray = [];

which is perfectly legitimate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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