如何将JavaScript变量数据获取到PHP,以便可以将纬度和经度数据插入数据库或以其他任何方式获取用户的位置并将其存储在数据库中。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<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) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
答案 0 :(得分:0)
似乎您需要使用AJAX将javascript变量的值传递给PHP。
在您的HTML文件(index.html)
index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getLocation()">Try It</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
//AJAX CALL THIS WILL PASS THE VALUE OF JAVASCRIPT TO PHP
$.ajax({
type: 'post',
url: 'ajax-processor.php',
data: {
lat: lat,
long: long
},
success: function(html) {
alert("Success");
}
});
}
</script>
在您的ajax文件(ajax-processor.php)中
$lat = $_POST['lat'];
$long = $_POST['long'];
//your code to insert to the database here using the $lat and $long variable
确保PHP文件的URL正确。
您可能会在我的博客文章https://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/
中了解有关AJAX以及如何将数据从JavaScript传递到PHP的更多信息。