将值从 Js 发送到 PHP

Sending values from Js to PHP

我要求用户在页面加载时的位置并将其设置为隐藏字段并尝试从他们那里读取到 php。 JS 代码有效,但是当我将它回显到 php 时,它显示为 null,并且在打印 'value is submitted' 之后它不断重新加载整个页面。

<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);