【问题标题】:Submit Form should display message after successful submit to Google Sheets提交表单应在成功提交到 Google 表格后显示消息
【发布时间】:2019-11-11 20:38:00
【问题描述】:

我正在尝试向 Google 表格提交表单。这一步是成功的,我得到了工作表中的所有数字。现在我想在提交表单并且 Google 表格的结果正常后显示一条成功消息。我该怎么做?

我在javascript和ajax中尝试过各种消息,但对它了解不多。我在下面展示了我的代码,你可以看看它。

<form name="submit-to-google-sheet">
                          <select class="form-control custom-form" name="country_code" id="country_code">
                            <option name="country_code" value="+91">India 91</option>
                            <option name="country_code" value="+93">Afghanistan 93</option>
                          </select>
                        </div>
                      </div>
                      <div class="row">
                        <div class="form-group spec-col col-md-8 col-lg-8 col-sm-12">
                          <input type="text" class="form-control custom-form" id="phone_no" name="phone_no" placeholder="Enter the Number">
                        </div>
                    </div>
                      <button class="btn btn-submit" id="submit" type="submit">Submit</button>
                      </div>
                    </form>

要向 Google 表格提交内容,这里是代码

<script>
      const scriptURL = 'GOOGLE SHEETS URL'
      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))
      })
    </script>

表单成功后,我可以在控制台看到一条成功消息。相反,我想在 HTML 中显示一个简单的单字行,非常感谢。一旦来自 Google 表格的回复正常并隐藏表单,您的提交就成功了。

编辑:其余代码可以参考这里:https://github.com/jamiewilson/form-to-google-sheets

【问题讨论】:

    标签: javascript html forms google-apps-script web-applications


    【解决方案1】:

    如果您使用 Google 表单将数据提交到 Google 表格,则表单设置中有一个设置,您可以在其中显示提交时的回复。无需代码。

    【讨论】:

    • 我没有使用 Google 表单。我直接使用 Google 表格。
    【解决方案2】:

    在按钮下方创建一个空白响应消息

    标签就是这样

    <button class="btn btn-submit" id="submit" type="submit">Submit</button>
    <p id="response_message"></p>
    

    现在在脚本中对 fetch 函数进行以下更改:

    form.addEventListener('submit', e => {
        e.preventDefault()
        var response_message = document.getElementById("response_message");
        fetch(scriptURL, { method: 'POST', body: new FormData(form)})
          .then(response => response_message.innerHTML = "Success!")
          .catch(error => response_message.innerHTML = "Error!")
      })
    

    【讨论】:

    • 执行此操作后,Google 表格不会添加条目。
    • 您在.then.catch 之后缺少关闭)
    • 即使在添加后也不会在 p 标签中显示响应。另外,我该怎么做才能关闭表格?表单关闭后,我应该能够显示该行。
    • 另外,它向我显示了消息,x 未在 Chrome 控制台中定义。
    • 太棒了。它现在正在工作。一件小事,你能告诉我,我怎样才能隐藏表单,然后显示消息?