我想在页面加载时将值从 JS 发送到 Rails

I want to send values from JS to Rails when the page is loaded

问题

页面加载时,将查询参数添加到 URL 后,我重定向到那个 URL。

但是,出现了死循环。

如何实现这一点,以便在加载页面时将值从 JS 发送到 Rails 而不会导致无限循环?

代码

window.onload = () => {
  function successGetPosition(position) {
    sessionStorage.setItem('latitude', position.coords.latitude);
    sessionStorage.setItem('longitude', position.coords.longitude);
    
    window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
  }

  function failGetPosition(error) {
        ...
  }

  options = {enableHighAccuracy: true};

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(successGetPosition, failGetPosition, {enableHighAccuracy: true});
    } else { 
      alert("Geolocation is not supported by this browser.");
    }
  }
 
  getLocation();
};

在这个函数中,你应该做的第一件事是检查 url 中是否包含纬度、经度查询参数。

function successGetPosition(position) {
    // parse the url looking for latitude and longitude params
    // if they are there, return immediately else proceed with the code below
    const [latitude, longitude] = myUrlParseFn();
    if (latitude && longitude) return;
    sessionStorage.setItem('latitude', position.coords.latitude);
    sessionStorage.setItem('longitude', position.coords.longitude);
    
    window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
  }