在提交表单之前运行获取函数时出现类型错误

问题描述

我遇到了这个错误

TypeError: NetworkError when attempting to fetch resource

尝试运行 *geocodeAddress*() 时。

如果我在没有 onsubmit="" 的情况下在该函数之外运行完全相同的代码,它会工作并将数据记录到控制台。这是为什么?

<?PHP 

// ...

?><!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="js/maps.js"></script>
  </head>
  <body>
    <form name="info" action="private/database.PHP" method="POST" onsubmit="return geocodeAddress()"> 
      <input type="text" name="surname" placeholder="性氏" required><br>
      <input type="text" name="given_name" placeholder="名字" required><br>
      <label for="male">
        <input type="radio" id="male" name="gender" required>
        男性
      </label>
      <label for="female">
        <input type="radio" id="female" name="gender">
        女性
      </label><br>
      <input type="text" name="email" placeholder="電子信箱" required><br>
      <input type="text" name="phone_number" placeholder="電話" required><br>
      <input type="text" id="address" name="address" placeholder="地址" required><br>
      <input type="hidden" name="latlng">
      <input type="date" name="cleaning_date" required><br>
      <input type="submit" name="form_submit">

      <script>
        function geocodeAddress() {
          fetch('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyDxn8WYv2aE5UrrufXLqeXKVYUnD-VyReA')
            .then(res => res.json())
            .then(data => console.log(data))
            .catch(error => console.log(error));
        }
    </script>
    </form>
  </body>
</html>

解决方法

解决了: 我将其更改为

后错误消失了
onsubmit="geocodeAddress(event.preventDefault())"

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...