我使用google maps api来获取用户位置。它以js变量返回数据。现在我想将这个js变量转换成php。我使用表单提交来转换变量,但问题是表单不是自动提交。
<?php
if(isset($_POST['loc'])){
?>
<script>alert("i am post!");
</script>
<?php
echo "i am post";
$country_name = $_POST['abc'];
echo $country_name."i am php";
}
else{
echo "i am php else";
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var country_name;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results)
if (results[1]) {
//formatted address
// alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "country") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
country_name = city.short_name;
document.forms[0].abc.value = country_name;
$("#def").submit();
document.write("form is submited");
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
<body onload="initialize()">
<form id="def" action="Db1.php" method="POST">
<input name="abc" id="abc" value="" />
<input type="submit" name="loc" />
</form>
</body>
<script>
$(function () {
alert(" i am jquery function");
window.onload(function () {
$("#def").submit();
});
});
</script>
<?php
}
?>
答案 0 :(得分:-1)
替换你的剧本
<script>
$(function () {
alert(" i am jquery function");
window.onload(function () {
$("#def").submit();
});
});
</script>
用这个
<script>
document.getElementById('def').submit();
</script>
修改强> 如果你想使用jquery提交而不是这个
$( "#def" )[0].submit();