好的,所以我在尝试找出如何将我保存在 localStorage 中的一些数据传递给我编写的 php 脚本时遇到了一些问题,这样我就可以将其发送到服务器上的数据库。我之前确实找到了一些代码(https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest),看起来它可以工作,但我没有运气。
这是我保存数据的代码,而不是试图通过我的 phpscript 传递它
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, showError, takeSnap);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function initialize(position) {
var lat = position.coords.latitude,
lon = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: "Current Location"
});
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unkown error occurred.");
break;
}
}
function storeLocal(position) {
if (typeof (Storage) !== "undefined") {
var lat = position.coords.latitude,
lon = position.coords.longitude;
localStorage.latitude = lat;
localStorage.longitude = lon;
}
else {
alert("Your Browser doesn't support web storage");
}
return
}
function snapShot() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(storeLocal, showError);
}
else {
alert("Geolocation is not supported by this browser.");
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("post", "snap.php?lat=" + localStorage.latitude + "&lon=" + localStorage.longitude, true);
oReq.send();
}
function reqListener() {
console.log(this.reponseText);
}
这是我编写的将值保存到数据库中的脚本
<?php
// Connecting to the database
mysql_connect("localhost", "username", "password");
mysql_select_db("db_name");
$latitude = mysql_real_escape_string($_GET["lat"]);
$longitude = mysql_real_escape_string($_GET["lon"]);
// Submit query to insert new data
$sql = "INSERT INTO locationsTbl(locID, lat, lon ) VALUES( 'NULL', '". $latitude ."', '". $longitude . "')";
$result = mysql_query( $sql );
// Inform user
echo "<script>alert('Location saved.');</script>";
// Close connection
mysql_close();
?>