問題
加載頁面后,將查詢引數添加到 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();
};
uj5u.com熱心網友回復:
在此函式中,您應該做的第一件事是檢查 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')}`;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460239.html
