javascript - 如何获取内部 html 数据的值以将值存储到数据库
问题描述
如何将此 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>
解决方案
似乎您需要使用 AJAX 将您的 javascript 变量的值传递给 PHP。
在您的 HTML 文件 (index.html) 中
索引.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 正确。
您可以在我的博客文章中阅读更多关于 AJAX 以及如何将数据从 JavaScript 传递到 PHP:https ://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/
推荐阅读
- react-native - 在 react native 上使用 Google gapi 浏览器库
- javascript - DataTables 无法读取未定义的属性“行”
- c++ - 如何检查字符串或字符是否有中文字符然后显示其他字符?
- azure - 代理无法连接到服务器
- c# - 使用正则表达式去除 html,但包含字符的标签除外
- eclipse - 本地主机上的服务器 Tomcat v9.0 服务器无法启动,并且子容器在启动期间失败
- c - 将单针 Arduino LED 矩阵划分为多个扇区
- python-3.x - 在 python 3 中捕获日志消息
- c# - Word 在打开文件时发现无法读取的内容错误
- javascript - IE 11 使用 Angular JS 冻结输入框(搜索)