我希望我的页面只加载一次,发生的事情是它不断重新加载,请帮我解决这个问题。
我希望代码在页面加载时立即运行,但我不希望它重新加载,它会继续重新加载我的页面。
除了重新加载问题以外,一切都很完美。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="getLocation()">
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(redirectToPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function redirectToPosition(position) {
window.location='j3.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
</script>
<?php
$lat=(isset($_GET['lat']))?$_GET['lat']:'';
$long=(isset($_GET['long']))?$_GET['long']:'';
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $long;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_contents = get_data($url);
$returned_contents_array = json_decode($returned_contents, true);
$results = $returned_contents_array['results'];
foreach($results as $result) {
echo $result['address_components'][0]['long_name'] . ", <br>";
}
?>
</body>
</html>
答案 0 :(得分:0)
如何检查坐标是否在函数内设置:
function getLocation() {
<?php if (!isset($_GET['lat']) || !isset($_GET['long'])) { ?>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(redirectToPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
<?php } ?>
}
这样,如果两个坐标参数都已设置,则函数体将为空并且不执行任何操作。