将PHP数组传递给JavaScript的问题 [英] Problems in passing PHP array to JavaScript

查看:60
本文介绍了将PHP数组传递给JavaScript的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解将PHP数组传递给Javascript的格式为:

I understand that the format for passing a PHP array to Javascript is:

<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>

我有一个php函数,将一些值存储在经度和纬度数组中。这些数组确实在php中保存了正确的值,因为php中的print_r()向我表明该数组是正确的。

I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.

print_r($latitude_array);
print_r($longitude_array);

现在,我以这种方式将此数组传递给JS:

Now, I pass on this array to JS in this manner:

<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>

一开始,当我打开HTML文件时,它显示了一个空数组(这是预期的因为尚未填充PHP数组)。然后用户输入一些内容,php数组充满了经度和纬度。这些值现在应该传递给JS。但是,此后它不会发出任何警报。我不确定数组是否成功传递给JS。我缺少什么?

In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?

推荐答案

尝试一下:

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

这篇关于将PHP数组传递给JavaScript的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆