onLoad 函数不断刷新页面

问题描述

美好的一天, 我有这个代码,假设页面加载后提交表单,这里的错误是它不断提交表单。

HTML 正文代码

<body onLoad="submitform();">

自动提交功能

    <script>
function submitform()
{
document.getElementById("gsend").submit();
}

HTML 表单

<FORM id="gsend" NAME="gsend" METHOD="POST" ACTION="index.PHP">
     <INPUT TYPE="text" NAME="long" ID="long" VALUE="" hidden>
     <INPUT TYPE="text" NAME="lat" ID="lat" VALUE="" hidden>


     </FORM>

JAVASCRIPT 是在页面加载成功时获取用户当前位置的方法

<script>
   
   function initGeolocation()
     {
        if( navigator.geolocation )
        {
           // Call getCurrentPosition with success and failure callbacks
           navigator.geolocation.getCurrentPosition( success,fail );
        }
        else
        {
           alert("Sorry,your browser does not support geolocation services.");
        }
     }

     function success(position)
     {

         document.getElementById('long').value = position.coords.longitude;
         document.getElementById('lat').value = position.coords.latitude
     }

     function fail()
     {
        // Could not obtain location
     }

   
</script>

这里的问题是代码不断重新加载。 我需要帮助

解决方法

您不需要 <form>,将位置存储到 cookie

index.php 检查 cookie 是否包含 lat

if(isset($_COOKIE['lat']){
  // cookie exist
  // do stuff
}

你可以用<body onLoad="submitform();">替换window.onload并删除表格,所以只需写<body>

script.js 同时检查 cookie

window.onload = (event) => {
  // check if cookie not exist
  if (!document.cookie.includes('lat=')) {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success,fail);
    }
    else {
      alert("Sorry,your browser does not support geolocation services.");
    }
  }
  else {
    // nothing here,cookie exist 
    // index.php should read the cookie for location and serve the content
  }
};


function success(position) {
  // set the cookies
  document.cookie = 'long=' + position.coords.longitude; + '; expires=Sun,1 Jan 2023 00:00:00 UTC; path=/'
  document.cookie = 'lat=' + position.coords.latitude + '; expires=Sun,1 Jan 2023 00:00:00 UTC; path=/'
  
  // reload the page and tell index.php to read the location inside cookies
  window.location.reload();
}

function fail() {
  alert("Sorry,you did not allow us to get geolocation services.");
}
,

您可以使用 fetch 调用将数据发送到服务器,而不必提交整个页面。

function initGeolocation() {
  if (navigator.geolocation) {
    // Call getCurrentPosition with success and failure callbacks
    navigator.geolocation.getCurrentPosition(success,fail);
  } else {
    alert("Sorry,your browser does not support geolocation services.");
  }
}

function success(position) {
  const data = {
    latitude: position.coords.latitude
    longitude: position.coords.longitude
  };

  fetch('index.php',{
      method: 'POST'
      headers: {
        'Content-Type': 'application/json',},body: JSON.stringify(data),})
    .then(function (response) {
       console.log('sent');
    })
    .catch(function(error) {
      console.error('Error:',error);
    });
}

function fail() {
  // Could not obtain location
}