我如何才能得到一个表单提交只有一次隐藏的值已经从谷歌地理编码服务更新

How can I get a form to submit only once hidden values have been updated from Google Geocoder service?

本文关键字:隐藏 更新 谷歌 一次 服务 编码 表单提交 一个      更新时间:2023-09-26

我有一个将在其中输入地址的表单,我想将相关坐标存储在我的数据库中。当我有一个单独的按钮用于地理编码时,它在更新表单中的隐藏值方面运行良好。然后单击一个单独的提交按钮,这些值将按照我的需要存储。

我真正想要的是点击一个按钮,检索坐标并提交表单,一旦这些值被检索,我下面的代码似乎没有完成这一点。

<script type="text/javascript">
var geocoder;
geocoder = new google.maps.Geocoder();
function codeAddress() {
  var address = document.getElementById("place_name").value;
  geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        document.getElementById("place_coordinates").value = results[0].geometry.location;
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  // document.forms["new_place"].submit();
}
</script>
<!-- the form -->
<input type="button" value="Submit" onclick="codeAddress()">

目前,表单正在提交,但没有"place_coordinates"隐藏值与表单一起提交。非常感谢您的帮助

如果您取消默认的表单提交,然后自己从geocode调用的回调函数中提交它,它应该可以做到。

不处理按钮的点击,而是处理表单的提交事件,确保返回false以取消默认提交(在本例中,我返回函数的结果,因此确保函数返回false):

<form onsubmit="return codeAddress(this);">
<script>
var geocoder;
geocoder = new google.maps.Geocoder();
function codeAddress(theForm) {
  var address = document.getElementById("place_name").value;
  geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        document.getElementById("place_coordinates").value = results[0].geometry.location;
        theForm.submit();
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  return false;
}
</script>

请注意,我已经将表单提交放在if/else的OK分支中,因此如果地理代码不成功,则不会提交表单。显然,你可以把它移到else语句之后但如果你想继续提交的话,它仍然在回调函数中

另外,请注意我将对表单的引用传递到函数中-您不必这样做,但我认为这样更简洁。