简体   繁体   English

使用json_encode将PHP数组传递给javascript会出错?

[英]Passing PHP array to javascript using json_encode giving errors?

I fetch some information from DB - shown here: 我从数据库中获取了一些信息-如下所示:

$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'"); 
    $handle->execute();
    $result = $handle->fetchAll(\PDO::FETCH_OBJ);
    //print_r($result);
    $x = 0;
    foreach($result as $obj){
         $resultArray[$x] = $obj->dropAddress;
         $x++;
    }

and then in my javscript: 然后在我的脚本中:

var count = "<?php echo json_encode($resultArray); ?>";

However I get the following error: 但是我收到以下错误:

Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ... 语法错误:意外数字-> var count =“ [” -33.8935642,151.20227810000006“,”-33.857653,151.20853699999998 ...

If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. 如果我用echo($ resultArray [0])替换json_encode($ resultArray),则值可以通过。 Not sure how to fix it because everything I've read uses this method. 不确定如何解决此问题,因为我阅读的所有内容均使用此方法。 TIA TIA

 var count = "<?php echo json_encode($resultArray); ?>"; 

You are returning the result of the json_encode inside of a JavaScript string. 您在返回的结果json_encode一个JavaScript字符串的内部 Your syntax error shows this: 您的语法错误显示如下:

 Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ... 

Unless there's a failure in coversion, json_encode returns valid JavaScript syntax , so you should just use it as-is without any adornments in your javascript: 除非出现故障,否则json_encode返回有效的JavaScript语法 ,因此您应按原样使用它,而在javascript中没有任何修饰:

var count = <?php echo json_encode($resultArray); ?>;

If you want to take into consideration the possibility of failure, then you can use this instead: 如果要考虑失败的可能性,则可以改用以下方法:

var count = <?php
     $tmp = json_encode($resultArray);
     echo ($tmp === false ? 'null' : $tmp);
?>;

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

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