谷歌地图&如果不包含php页面,如何将变量从php页面传递到另一个

时间:2015-03-11 09:28:05

标签: php jquery ajax google-maps variables

我正在研究这个例子:“将PHP / MySQL与谷歌地图一起使用” https://developers.google.com/maps/articles/phpsqlajax_v3

我知道这个教程之前已经涉及很多,但我找不到我想要的答案,希望有人可以提供帮助。

我正在尝试使用标记显示Google地图。每个标记都是书籍图标。书籍按类别组织(我在我的数据库中将其称为“类型”)。这个想法是用户可以选择他们想要的书籍类别,然后只有这些书籍才会显示在地图上。

我的问题是我无法让FORM select工作,需要将“type”变量从index.php传递到页面phpsqlajax_genxml2.php,以便查询数据库。

我的问题是 - 如何将php变量$ type输入到phpsqlajax_genxml2.php页面?

phpsqlajax_genxml2.php页面不包含在index.php页面中,但有一个downloadUrl函数: downloadUrl(“phpsqlajax_genxml2.php”,函数(数据)

以下是我的文件。提前致谢

的index.php

    <?php
    // Get parameters from URL
    $type = $_GET["type"];
    ?>


    <!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>PHP/MySQL & Google Maps Example</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      'Murder Mystery': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png'
      },
      'Travel Guide': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'
      },
      'Romance': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
      },
      'Short Story': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
      },
      'Thriller': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      },
      'Comedy': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
      },
      'Graphic Novel': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_white.png'
      },
      'Satire': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png'
      }

    };
</script>

<script type="text/javascript">

//Check if browser supports W3C Geolocation API

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } else {
  alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}

function errorFunction(position) {
  alert('Error!');
}

//If successful geolocation then draw the map, show my coords on the map, and pull in the icons

function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
        var map = new google.maps.Map(document.getElementById("map"), 
        {
        center: new google.maps.LatLng(lat, lng),
        zoom: 13,
        mapTypeId: 'roadmap'
        });

        var infoWindow = new google.maps.InfoWindow;

      // SQL to XML file
      //downloadUrl("phpsqlajax_genxml2.php?type=" + type, function(data) {
      downloadUrl("phpsqlajax_genxml2.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + "<i>" + type + "</i>";
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}

    //]]>

  </script>

  </head>

<body onload="successFunction(position)">

<div id="map" style="width: 500px; height: 400px"></div>

<form action="<?php $_PHP_SELF ?>" method="GET">
<select name="type">
  <option value="Murder Mystery">Murder Mystery</option>
  <option value="Travel Guide">Travel Guide</option>
  <option value="Romance">Romance</option>
  <option value="Short Story">Short Story</option>
  <option value="Thriller">Thriller</option>
  <option value="Comedy">Comedy</option>
  <option value="Graphic Novel">Graphic Novel</option>
  <option value="Satire">Satire</option>
</select>
<input type="submit" value="Submit" />
</form>

</body>

</html>

phpsqlajax_genxml2.php

<?php
// Get parameters from URL
$type = $_GET["type"];

include ("inc/DB_connect.php");

//Using PHP's echo to Output XML

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
}


// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) 
{
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table
//$query = "SELECT * FROM `markers` WHERE 1";
$query = "SELECT * FROM `markers` WHERE `type` = '$type'";
$result = mysql_query($query) or die(mysql_error());

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result))
{
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>

1 个答案:

答案 0 :(得分:1)

因此,如果您想将数据从一个PHP文件传递到另一个PHP文件,在这种情况下,您有两个选项:Cookie和会话:

<强>曲奇:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

<强>会话

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

会话和Cookie之间的最大区别在于,如果您正在使用会话,则变量的值将存储在服务器上;如果您正在使用Cookie,则会在客户端上存储。除非您希望数据在会话之间保持不变,否则我无法想出使用Cookie而不是会话的任何合理理由,但即使这样,将数据存储在数据库中也可能更好,并在此基础上检索它用户名或ID。

修改

还支持另外一种方法,您可以在JQuery调用中传递该变量,如下所示:

在你的第一个档案中:

jQuery('#map').load('Firstfile.php?type=<?php echo($type);?>');

在你的第二个档案中

$type = $_GET['type'];

给这个人一个机会!

摘自Passing php variable from one file to another?