Writing to javascript array in php loop

I have a php loop that reflects geolocation values. How can I get it to write these values ​​to a javascript array so that I can use them to plot points on HTML5 canvas?

The php loop is as follows

<ul id = "geo-list">
    <?php foreach($data as $phrase) { ?>
        <li><?php
            if ($phrase->geo != false) {
                echo " | From (";
                echo $phrase->geo->coordinates[0];
                echo ",";
                echo $phrase->geo->coordinates[1];
                echo ")";
            } else {
                echo " | No Location Data";
            }
        ?>
        </li>
    <?php  } ?>
</ul>
+2
source share
4 answers

You tried

var myJavascriptData = <?= json_encode($php_data) ?>;
+5
source

You might want to use the JSON library for PHP.

+2
source

javascript - "" html.

html :

echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
    echo "\n <TR>";
    echo "\n<TD>" . $cf['KEY'] . "</TD>";
    echo "\n<TD>" . $cf['COL1'] . "</TD>";
    echo "\n<TD>" . $cf['COL2'] . "</TD>";
    echo " </TR>";
  }
  echo "\n</TABLE>";

javascript: -

var dtab = document.getElementById("DATATAB");
var rows  = dtab.getElementsByTagName("tr"); 
for (var r = 0; r < rows.length ; r++) {
   row = rows[r];
   item_key  = row.cells[0].innerHTML;
   item_col1 = row.cells[1].innerHTML;
   item_col2 = row.cells[2].innerHTML;
   // do your thing here ......
}

AJAX, , dojo javascript REST.

, XML JSON, .

0

, script .

javascript, .

, - :

<script type="text/javascript">
    var coords = new Array(2);
    coords[0] = new Array(2);
    coords[0][0] = 123.45;
    coords[0][1] = 987.65;
    coords[1] = new Array(2);
    coords[1][0] = 234.56;
    coords[1][1] = 876.54;
</script>

, .

( ) , , javascript. :

<script type="text/javascript">
    var coords = [[123.45,987.65],[234.56,876.54]];
</script>

so in your loop inside php you will create a string that will eventually contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside of your loop, you wrap it in script blocks and output it to the page.

0
source

Source: https://habr.com/ru/post/1745075/


All Articles