我想追踪用户位置并保存到数据库中。 我在加载页面的时候,使用地理位置脚本跟踪用户位置数据到mysql数据库。但是地理位置数据并没有插入到数据库中。以下是代码
<?php
require('config.php');
$data1=$_POST['location'];
mysqli_query($con,"insert into table(raw) values('$data1')");
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body onload="getLocation()">
<form method="post" action="">
<input name="location" id="demo" type="hidden" /></form>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var url = "https://www.google.com/maps/@"+latlon;
x.innerHTML = url;
}
</script>
</body>
</html>
你做的方式不对,你看代码的执行顺序,正文会在表单之前加载,然后...。<form> </form>
因为,只有字段,即,是隐藏的,不包含任何值。为了达到这个目的,你需要在你的代码中做以下操作。
<pre><form><input type="hidden" id="demo" name="location" value="" />
<script type="text/javascript">
var elem = document.getElementById("demo");
elem.value = navigator.geolocation.getCurrentPosition(showPosition);
</script></form>