gpt4 book ai didi

javascript - 如何将客户端数据发送到服务器端

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:31 27 4
gpt4 key购买 nike

我正在使用 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 是一个异步函数,这意味着:

  1. 您点击按钮
  2. 触发 Onclick 函数
  3. 表单已提交
  4. 设置表单值的回调函数会运行(如果您没有离开页面,则会运行)

在数据可用之前,您需要避免提交表单。

  • 使用 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>

关于javascript - 如何将客户端数据发送到服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54720632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com