我正在创建一个上传文件到服务器的网页,在上传文件之前,我的网页收集了用户的地理位置,但 "returnLocation() "函数不能工作,我的代码绕过了获取GeoLocation的javaScript代码。
JavaScript:
var x = document.getElementById("LocationStatus");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Browser not supported!";
return false;
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.cookie="lat="+position.coords.latitude+"lon="+position.coords.longitude;
return true;
}
function error(msg) {
var s = document.querySelector('#status');
msg = msg.message ? msg.message : msg;
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
return false;
}
</script>
HTML:
<form name="form" method="post" action="upload.php" enctype="multipart/form-data" >
<input type="file" name="my_file" />
<button type="submit" onclick="return getLocation()">Upload File</button>
</form>
你永远不要在调用一个函数时提到 return
语句中。
将您的代码改为
<button type="submit" onclick="callFunction();">Upload File</button>
现在你 getLocation()
函数将被调用。
而在你的代码中,你只是调用了主函数,但其中的函数并没有被调用,所以在你的代码中,你只是调用了主函数,但其中的函数并没有被调用。
你也给他们打个电话吧
<script>
function callFunction(){
getLocation();
showPosition(position);
error(msg);
}
var x = document.getElementById("LocationStatus");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Browser not supported!";
}
return false;
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.cookie="lat="+position.coords.latitude+"lon="+position.coords.longitude;
return false;
}
function error(msg) {
var s = document.querySelector('#status');
msg = msg.message ? msg.message : msg;
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
return true;
}
</script>
使用onsubmit="getLocation() "代替onclick,并在表单元素上使用。
<form method="POST" onsubmit="getLocation()" action="upload.php"
enctype="multipart/form-data" >
<input type="file" name="my_file" />
<button type="submit">Upload File</button>
</form>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Browser not supported!";
return false;
}
}