我遇到了将google脚本页面重定向回我的自定义网址的问题。脚本当前正在执行,但我不能让它在完成执行后重定向回到它的上一页。
继承script.gs代码:
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
var name= String(mailData.name);
var message= String(mailData.message);
var email= String(mailData.email);
var all= ("Name: "+name+"\nReply address: "+email+"\nMessage: "+message);
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
MailApp.sendEmail({
to: String(sendEmailTo),
subject: String(mailData.subject),
replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
body: String(all)
});
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
这是我的HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2;url=xxxxxxxxxx.com" />
<base target="_top">
</head>
<body>
Click <a href="xxxxxxxxxx.com">here</a> to go back.
</body>
</html>
使脚本打开index.html页面的最佳方法是什么,以便我可以轻松地重定向回自定义URL?
答案 0 :(得分:2)
这是处理POST请求后重定向的有效示例。
var REDIRECT_URL = "http://www.stackoverflow.com";
function doPost(e) {
Logger.log("POST request");
Logger.log(e)
return redirect();
}
function doGet() {
Logger.log("GET request");
var template = HtmlService.createTemplateFromFile("form");
template.url = ScriptApp.getService().getUrl();
return template.evaluate();
}
function redirect() {
return HtmlService.createHtmlOutput(
"<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form action="<?= url ?>" method="post">
<input type="text" name="test_field" value="test data">
<button type="submit">Submit form</button>
</form>
</body>
</html>
当我访问已发布的网络应用程序(即使用GET请求)时,系统会显示一个简单的表格。
提交该表格(即使用POST请求)后,我立即被重定向到http://www.stackoverflow.com
。
此输出在脚本日志中捕获:
[18-06-19 10:39:04:731 PDT] POST request
[18-06-19 10:39:04:732 PDT] {parameter={test_field=test data}, contextPath=, contentLength=20, queryString=, parameters={test_field=[test data]}, postData=FileUpload}
关于代码示例,您具有:
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
这没有意义,因为您对doGet()
的结果不做任何事情。为了使doGet()
调用有用,请将以下内容替换为:
return doGet();