简体   繁体   English

2个PHP变量中的最大值,如何从脚本传递到jQuery?

[英]Max of values in 2 PHP variables, how to pass from script to jQuery?

I want to use gmaps.js to add map markers onto a map on my site. 我想使用gmaps.js将地图标记添加到我网站上的地图上。 I'm using a PHP Script to get the latitude and longitude from my DB, however I'm using 我正在使用PHP脚本从数据库中获取经度和纬度,但是我正在使用

while($dbrowinfo = mysqli_fetch_assoc($rowfields))

Therefore the information comes to an end after the Database query has been ran. 因此,信息在数据库查询运行后就结束了。 Per page there will be a maximum of 10 sets of data, both with a long and lat value (therefore 20 individual variables). 每页最多包含10组数据,均具有long和lat值(因此有20个独立变量)。

Is there any way to use the variables from PHP to pass to jQuery before the script is ran? 在脚本运行之前,是否可以使用PHP中的变量传递给jQuery? Can't really get my head around it as jQuery is client and PHP is serverside... 由于jQuery是客户端,PHP是服务器端,因此我无法真正解决这个问题。

Thanks for your time 谢谢你的时间

If you are asking if there is a way to pass variables from PHP to JavaScript before the JQuery script has run, the answer is yes, definitely. 如果您问是否有一种方法可以在运行JQuery脚本之前将变量从PHP传递给JavaScript,答案肯定是肯定的。 All the PHP will run before any of the JavaScript, so, you can simply output the data you want as JavaScript variables, like so: 所有PHP将在任何JavaScript之前运行,因此,您可以简单地将所需数据作为JavaScript变量输出,如下所示:

<html>

<?php
// Load the data into your PHP variables
$dataA = "some data";
$dataB = "some more data";
$dataC = 245; // numeric data
?>
<body>
    <!-- now open a script tag -->
    <script>
    var jsVar1 = "<?= $dataA ?>";// If outputting string, you need to add quotes for js
    var jsVar2 = "<?= $dataB ?>"; 
    var jsVar3 = <?= $dataC ?>; // No quotes needed for a number

    $(document).ready(function(){
        console.log("data from php: " + jsVar1 + " " + jsVar2 + " " + jsVar3);
    });
    </script>
</body>

</html>

Put the values in a PHP array, and then encode them into a Javascript array with json_encode 将值放入PHP数组,然后使用json_encode将其编码为Javascript数组

$coords = array();
while ($row = mysqli_fetchassoc($rowfields)) {
    $coords[] = array('lat' => $row['lat'], 'lng' => $row['lng']);
}
echo '<script>var coords = ' . json_encode($coords) . ';</script>';

This defines a Javascript variable coords that contains an array of objects, like: 这定义了一个Javascript变量coords ,其中包含对象数组,例如:

var coords = [
    { lat: 50.0, lng: 101.1 },
    { lat: -20.8, lng: 55.3 },
    ...
];

You can then use this array in your jQuery code. 然后,您可以在jQuery代码中使用此数组。

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

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