我试图将json_encode从PHP传递给JavaScript

时间:2013-02-22 19:38:12

标签: php javascript

我正在尝试使用json_encode

将数组从PHP传递到javascript

但是当我提醒值时,我只看到“对象对象等”

当我var_dump它我看到实际的数组但它没有在警告中显示它们

任何帮助将不胜感激

此致

这是var_dump

array(1) {
  [0]=>
  array(2) {
    ["id"]=>
    string(19) "3.0268"
    ["postcode"]=>
    string(137) "hello"
  }
}

array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    string(19) "3.0268070455319E+17"
    ["postcode"]=>
    string(137) "ECMWF continues its flip-flopping, still a temp drop next week & #snow risk but then no rise, http://t.co/tBlg9Ihs #ukweather #uksnow"

} 代码

<?php

 $con =  mysql_connect('localhost', 'root', '');
    mysql_select_db('test');

   $result = mysql_query("SELECT * FROM address");

$arr = array();
while($row = mysql_fetch_assoc($result)) {
    $arr[] = $row; 

}

?>

<script>

var test = <?php echo json_encode($arr); ?>;
alert(test);

</script>

1 个答案:

答案 0 :(得分:5)

alert会调用toString()传递给它的内容。您可能需要console.logtest是一个对象,默认情况下是alert中打印的对象。

示例:

alert({a:1,b:2}) // => [object Object]
({a:1,b:2}).toString() // => "[object Object]"