好的,所以我在試圖找出如何將我保存在localStorage中的一些數據傳遞給我編寫的php腳本時遇到了一些問題,所以我可以將它們發送到服務器上的數據庫。我之前找到了一些代碼(https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest),看起來好像可以工作,但我沒有運氣。如何將保存的localStorage Web數據傳遞給php腳本?
這裏就是我保存數據的代碼,不是試圖通過它在我的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();
?>
是的,但我並不確定如何在我的情況下使用POST請求,因爲我沒有從窗體的字段中獲取信息。它的工作方式是我在頁面上創建了一個按鈕。它有一個事件監聽器,它正在尋找一個圖像的點擊,而不是抓取地理位置數據並保存它。 – RenegadeScar
@RenegadeScar我明白,但你所做的只是改變'oReq.open(「get」'to'oReq.open(「post」'。然後在PHP中,你用'$ _POST'而不是'$ _GET ' – Ian
ooooh,我明白了。對不起,我對javascript和一般的程序是最新的。謝謝我會試試。 – RenegadeScar