微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我遇到了这个错误

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())"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。