[英]Sending values from Js to PHP
我在頁面加載時詢問用戶的位置並將其設置為隱藏字段並嘗試從他們的 php 中讀取它。 JS 代碼有效,但是當我將其回顯到 php 時,它顯示為 null,並且在打印“提交值”后,它會不斷重新加載整個頁面。
<script>
var x = document.getElementById(\"latitude\");
var y = document.getElementById(\"longitude\");
var a;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
} else
{
x.innerHTML = \"Geolocation is not supported by this browser.\";
}
}
function showPosition(position)
{
x.value = position.coords.latitude;
y.value= position.coords.longitude;
submitform();
}
function submitform()
{
document.forms[\"locform\"].submit();
console.log(\"Value is sumitted\");
}
getLocation();
</script>
<form action='abc.com/list' id='locform' method='get'>
<input type='hidden' id='latitude' name='latitude'>
<input type='hidden' id='longitude' name='longitude'>
</form>
$users_postal=$_GET['latitude'];
echo($users_postal);
問題是您的 javascript 代碼在頁面加載之前執行。 您必須等待所有 HTML 加載然后運行您的 js 代碼。
您可以通過添加更改表單和腳本標記位置來實現這一點。 在 HTML 代碼之后完全編寫您的 js。
<form action='abc.com/list' id='locform' method='get'>
<input type='hidden' id='latitude' name='latitude'>
<input type='hidden' id='longitude' name='longitude'>
</form>
<script>
// you js code here
</script>
/then write PHP code
$users_postal=$_GET['latitude'];
echo($users_postal);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.