简体   繁体   English

将字符串从.php传递到.html中的Javascript函数

[英]Pass string from .php to Javascript function in .html

I want to pass the $string variable from my .PHP file to the javascript variable heatmapdata = [string] in the initMap() function in my .html file. 我想将$ string变量从我的.PHP文件传递到.html文件中initMap()函数中的javascript变量heatmapdata = [string]。 How can I do that? 我怎样才能做到这一点?

HTML 的HTML

<!DOCTYPE html>
<html>
<head>
<script>
function showString(time) {
  if (time=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","getstring.php?q="+time,true);
  xmlhttp.send();
}
</script>
<script>
            var map, heatmap;
            var heatmapdata;

            function initMap() {
                /* Hands over the string of the scriptlet to a variable */
                heatmapdata = [string];
                map = new google.maps.Map(document.getElementById('map'), {
                zoom: 2,
                center: {lat: 37.775, lng: -122.434},
                mapTypeId: google.maps.MapTypeId.SATELLITE
              });
              heatmap = new google.maps.visualization.HeatmapLayer({
                data: heatmapdata,
                map: map
              });
            }
        </script>
</head>
<body>
<form>
<select name="users" onchange="showString(this.value)">
<option value="">WholeWorldAllTime:</option>
<option value="1">Whole World 1 Hour</option>
</select>
</form>
<br>
<div id="txtHint"><b>String will be listed here.</b></div>
</body>
</html>

.PHP .PHP

<?php
$q = intval($_GET['q']);
$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
    die('Could not connect: ' . pg_errormessage($con));
}

$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);

    $string = "";
while($row = pg_fetch_assoc($result)){
    $lat = $row['latitude'];
    $lon = $row['longitude'];
    $string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo $string;
pg_close($con);
?>

You can make an AJAX request to the PHP file to retrieve the variable: 您可以向PHP文件发出AJAX请求以检索变量:

$.getJSON('path/to/php/file.php', function(data) {
    heatmapdata = data.value;
});

In your PHP file (this must be the only output in the file: 在您的PHP文件中(这必须是文件中唯一的输出:

echo '{"value": "'.$string.'"}';

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

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