簡體   English   中英

HTML 表單到 Google 電子表格

[英]HTML form to Google spreadsheet

我正在處理將數據提交到 Google 電子表格的 HTML 表單。 本教程向我展示了技巧並且對我來說效果很好,盡管它不包括返回用戶她/他提供的信息的確認頁面。 不知何故,我找到了一種方法,但我無法使確認頁面包含用戶提供的信息。

我發現了幾個與這個問題接近的問題,但大多數問題都通過 innerHTML(在表單底部/頂部添加的小文本,不是我的意圖)和/或我無法讓它們工作來解決。

這是我的代碼:

</head>
<body>
    <form name="submit-to-google-sheet">
      <input name="email" type="email" placeholder="Email" required><br>
      <input name="nombre" type="text" placeholder="Nombre"><br>
      <input name="apellido" type="text" placeholder="Apellido"><br>

      <button type="submit">Enviar</button>
    </form>
    
    <script>
      const scriptURL = 'https://script.google.com/blabla'
      const form = document.forms['submit-to-google-sheet']
    
      form.addEventListener('submit', e => {
        e.preventDefault()
        fetch(scriptURL, {method: 'POST', body: new FormData(form)})
          .then(response => console.log('Success!', response))
          .catch(error => console.error('Error!', error.message))
        window.location.href = "conf.php";
      })
    </script>
</body>

和確認頁面(conf.php):

<head>
    
</head>
<body>
    <p>Text.</p>
    <?php
    setlocale(LC_TIME,"es_ES");
    
    echo 'Nombre: ' . $_POST ["nombre"] . '<br>';
    echo 'Apellido: ' . $_POST ["apellido"] . '<br>';
    echo 'E-mail: ' . $_POST ["email"] . '<br><br>';
    echo strftime("Fecha de inscripción: %A %e de %B de %Y a %H:%M") . '<br>';
    ?>
    <button onclick="imprimir()">Imprimir confirmación</button>
    <p>Text.</p>
    <button onclick="volver()">Volver</button>
    <script>
      function imprimir() {
        window.print();
      }
      function volver()     {
        window.location.href = "index.html";
      }
    </script>
</body>

首先十分感謝。

有一個 javascript 語法錯誤。 以下無法編譯。

function(window.location.href = "confirm.php";)

請更正。

window.location.href = "confirm.php";

毫無疑問,帖子請求被發送到https://script.google.com/blabla ,在他的標題中包含表單數據。 所以你可以在confirm.php 控制這個請求並回顯如下結果。

//confirm.php
<?php
//get any kinds of data from https://script.google.com/blabla
...
//response the result
echo("<p>Successfully posted!</p><a onclick='window.location.history.back()'>Go back</a>");

箭頭函數中不能有多行而不用大括號括起來,因此您需要更正fetch

fetch(scriptURL, {
    method: 'POST',
    body: new FormData(form)
  })
  .then(response => {
      console.log('Success!', response);
      window.location.href = "conf.php";
    }
  )
  .catch(error => console.error('Error!', error.message))

此外,您很可能總是會收到錯誤消息,因為您正在向假端點發送請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM