如何将数组从php动态复制到javascript? [重复]

时间:2022-12-21 21:33:52

This question already has an answer here:

这个问题在这里已有答案:

I'm writing code in PHP and HTML for the server side coding of a GPS tracking system. The PHP code will access the coordinates of the GPS from a database. I've found HTML code to display those coordinates on a map(as a Polyline). In the database, a new tuple will be added almost every minute, so we cannot specify how many elements are in the array, before hand.

我正在用PHP和HTML编写代码,用于GPS跟踪系统的服务器端编码。 PHP代码将从数据库访问GPS的坐标。我发现HTML代码可以在地图上显示这些坐标(作为折线)。在数据库中,几乎每分钟都会添加一个新元组,因此我们无法预先指定数组中有多少元素。

How do I dynamically copy an array from php to javascript?

如何将数组从php动态复制到javascript?

this is the website with the code for drawing the polyline.

这是带有绘制折线的代码的网站。

2 个解决方案

#1


3  

How do I dynamically copy an array from php to javascript?

如何将数组从php动态复制到javascript?

You can’t “copy” it at all, because PHP and JavaScript are two completely different worlds.

你根本无法“复制”它,因为PHP和JavaScript是两个完全不同的世界。

What you can do is transfer it in text form – for example by encoding it as JSON in your PHP script, echo-ing it out as JS code (or request it from the server in a new HTTP request via JSONP/AJAX), and parse it back into a JavaScript object or array structure.

您可以做的是以文本形式传输它 - 例如,在PHP脚本中将其编码为JSON,将其作为JS代码回显(或通过JSONP / AJAX在新的HTTP请求中从服务器请求),以及将其解析回JavaScript对象或数组结构。

#2


1  

Give something like this a try:

尝试这样的东西:

<?php
$arr = array('cat', 'dog', 'mouse');
?>

<body>
    <script>
        var jsArr = <?php echo json_encode($arr); ?>;
        console.log(jsArr);
    </script>
</body>

Should output

["cat", "dog", "mouse"] 

in console

#1


3  

How do I dynamically copy an array from php to javascript?

如何将数组从php动态复制到javascript?

You can’t “copy” it at all, because PHP and JavaScript are two completely different worlds.

你根本无法“复制”它,因为PHP和JavaScript是两个完全不同的世界。

What you can do is transfer it in text form – for example by encoding it as JSON in your PHP script, echo-ing it out as JS code (or request it from the server in a new HTTP request via JSONP/AJAX), and parse it back into a JavaScript object or array structure.

您可以做的是以文本形式传输它 - 例如,在PHP脚本中将其编码为JSON,将其作为JS代码回显(或通过JSONP / AJAX在新的HTTP请求中从服务器请求),以及将其解析回JavaScript对象或数组结构。

#2


1  

Give something like this a try:

尝试这样的东西:

<?php
$arr = array('cat', 'dog', 'mouse');
?>

<body>
    <script>
        var jsArr = <?php echo json_encode($arr); ?>;
        console.log(jsArr);
    </script>
</body>

Should output

["cat", "dog", "mouse"] 

in console