Call php from javascript


Call php from javascript

我有一个索引.php它包含JS和PHP代码。PHP 代码从 iOS 应用程序读取 GPS 坐标,JS 将这些坐标读回以显示在 Web 应用程序上。

我一直在弄清楚如何每隔几秒钟调用 PHP,以便我可以获得新的坐标。我对如何处理这个问题一无所知,如果我需要为此目的调用同一个文件,这似乎是一种递归。

"刷新"PHP代码并读取新坐标的最佳方法是什么?这是我的代码:

<?php include_once('location.php') ?>
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>My GeoLocation</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

    <script>
var map;
google.maps.visualRefresh = true;  
function initialize() {
  var myLatlng = new google.maps.LatLng(<?php echo $current_lat ?>, <?php echo $current_long ?>);
  var mapOptions = {
    zoom: 14,
    center: myLatlng
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Hello World!'
  });
  yourFunction();
}

function yourFunction(){
alert ("<?php echo $current_lat ?>, <?php echo $current_long ?>"); --> here I get the same coordinates 
//Will add code here to display the new lat/long once I figure out how to refresh them 
    setTimeout(yourFunction, 1000);
}
google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "aaaaaa", "bbbbbb", "location111");
if ($con1->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$db_selected = mysql_select_db('location111');
if (!$db_selected) {
    die ('Can''t use foo : ' . mysql_error());
}
if (!empty($lat)) {
  $sql = "INSERT INTO LocationInfo (latitude, longitude) 
                VALUES ('$lat', '$long');";
  mysql_query($sql) or die ('Error updating database: ' . mysql_error());
 }
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
    $column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];

?>

您可能正在寻求实现 AJAX。

你要做的是将PHP代码与Javascript分开,并创建一个只输出坐标的页面。

然后你从Javascript调用这个页面,你将在一个变量中得到结果。

实现这一点的最简单(但不是最好的)方法是使用 jQuery: http://api.jquery.com/jquery.ajax/

$.ajax("mypageurlhere", {
  success: function(data) {
    console.log("Data: " + data);
  },
  error: function() {
    console.log("Error loading data");
  }
});