我正在使用 HTML5 中内置的地理定位 API,但主要问题是,我想将地理定位 Api 的结果存储在我的数据库中。所以我的主要问题是如何将此详细信息或结果发送到我的主文件(服务器端)?
我制作了一个空表单,并通过脚本标记插入了两个输入隐藏标记,并通过使用按 ID 选择标记将结果存储在其中,然后只需将其值更改为我想要的结果。但我在后端文件中收到空字符串。
// EJS FILE
<body>
<p>Click to get your coordinates.</p>
<form action="/" method="POST">
<input type="hidden" name="lat" id="lat" value="">
<input type="hidden" name="long" id="long" value="">
<input type="hidden" name="test" id="test"value="">
<button type="submit" onclick="Onclick()">Try It</button>
</form>
<p id="demo"></p>
<script>
function Onclick(){
var x = document.getElementById("lat");
var y = document.getElementById("long");
var z = document.getElementById("test");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
console.log(position.coords);
x.value = position.coords.latitude
y.value = position.coords.longitude;
});
} else
z.value = "Geolocation is not supported by this browser.";
}
</script>
(Please give me answer in JS only )
我是NodeJs新手,在发布这个问题之前我搜索了很多,没有得到所需的答案。我非常感谢您花费宝贵的时间来解决这个问题。
当我单击按钮并在服务器端检查它时,我没有得到所需的结果,而是得到了空值,请在这部分帮助我!
getCurrentPosition
是一个异步函数,这意味着:
- 您点击按钮
- 触发
Onclick
函数
- 表单已提交
- 设置表单值的回调函数会运行(如果您没有离开页面,则会运行)
在数据可用之前,您需要避免提交表单。
- 使用
addEventListener
绑定(bind)您的事件处理程序
- 防止表单的默认行为
- 数据可用后使用 JS 重新提交表单
// Bind the event listener here
var form = document.querySelector('form');
form.addEventListener("submit", submit_geo_coords);
// Add the event paramater to the function
function submit_geo_coords(event) {
event.preventDefault(); // Stop normal submission of the form
var x = document.getElementById("lat");
var y = document.getElementById("long");
var z = document.getElementById("test");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position.coords);
x.value = position.coords.latitude
y.value = position.coords.longitude;
form.submit(); // Resubmit the form when the data is available
});
} else
z.value = "Geolocation is not supported by this browser.";
}
<p>Click to get your coordinates.</p>
<form action="/" method="POST">
<input type="hidden" name="lat" id="lat" value="">
<input type="hidden" name="long" id="long" value="">
<input type="hidden" name="test" id="test" value="">
<button type="submit">Try It</button>
</form>
我是一名优秀的程序员,十分优秀!