从 Google Web App 中的 doPost() 重定向,带有 App 脚本的 HTML 表单

Jur*_*eri 4 forms web-applications google-apps-script

假设我有一个包含各种输入的 HTML 文件。根据这些输入,我想发送一封电子邮件,然后显示感谢信息或重定向到感谢页面。

我正在 doGet() 中加载 index.html 文件,如下所示:

function doGet(){
    var template = HtmlService.createTemplateFromFile('index');
    template.action = ScriptApp.getService().getUrl();
    return template.evaluate();
}
Run Code Online (Sandbox Code Playgroud)

在 doPost(e) 函数中添加我需要的实现,将代码部署到 Web 应用程序中,填写表单并提交后,除了最后一点之外,一切似乎都运行良好。我想显示一个输出消息或重定向到一个感谢页面,或者类似的东西,但我看到的只是一个空白页面,那里本来是 HTML 表单。

我试过了:

function doPost(e) {
    //all logic
    return ContentService.createTextOutput("Thank you");
}
Run Code Online (Sandbox Code Playgroud)

和..

function doPost(e) {
    //all logic
    return ContentService.createTextOutput(JSON.stringify(e.parameter));
}
Run Code Online (Sandbox Code Playgroud)

和..

function doPost(e) {
    //all logic
    var htmlBody = "<h1>Thank you.</h1>";
    return HtmlService.createHtmlOutput(htmlBody);
}
Run Code Online (Sandbox Code Playgroud)

和..

function doPost(e) {
    //all logic
    var template = HtmlService.createTemplateFromFile('Thanks');
    return template.evaluate();
}
Run Code Online (Sandbox Code Playgroud)

在所有列出的情况下,HTML 表单似乎都消失了,我只能看到一个空白屏幕。

有任何想法吗?

Ant*_*iev 7

在 GAS 中,通过 Web 应用程序发送 POST 请求并不像看起来那么简单。继续尝试一个小实验:将以下 JS 代码添加到由 doGet() 函数提供的 HTML 页面,就在 <body> 结束标记之前:

... 
<script>
console.log(window.location);
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

在控制台中检查输出时,您可能会得到如下信息:

在此处输入图片说明

问题在于以“/exec”结尾的网络应用程序 URL 实际上并未链接到 self. Ratner,googleusercontent.com链接是您打开链接和表单时重定向到的 URL。但是,为了使表单提交工作,POST 请求应该发送到您的网络应用程序的“已发布”URL(以“/exec”结尾的那个)。

因此,您必须通过实现自己的路由来覆盖默认值。有很多方法可以实现这一结果 - 这是最简单的一种:

    <form method="post" action="<?!= ScriptApp.getService().getUrl() ?>">
    <input type="submit" value="submit">
    </form>
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉 <?!= ?> 符号,请查看 GAS https://developers.google.com/apps-script/guides/html/templates 中有关 scriptlet 和 HTML 模板的部分

基本上,在将原始 HTML 发送到浏览器进行渲染之前,Web 应用程序 URL 会被强制打印到模板中。这可确保您在“提交”事件发生时点击正确的 URL。