我尝试了这段代码,它几乎可以工作。但这段代码有一个问题。
什么不起作用
如果没有上传文件,发送按钮将不起作用。
努力实现
所有输入字段都应为必填项(姓名、电子邮件、电话、消息)。 但上传文件必须是可选字段。
Addditional:我尝试添加功能,例如在用户成功提交表单后自动向收件人发送电子邮件。但我无法编写该部分的代码,如果有人知道如何做到这一点,非常欢迎添加此自动电子邮件功能。
这是我尝试过的代码[(code.gs),(index.html),(库id)]
图书馆编号
1CcBYkrGSeBRgphHUE92vWInyULOcJ1Ub6eFUR0_gI1h9I6whLjXtDA-P
代码.gs
function doGet() {
return HtmlService.createTemplateFromFile('index').evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
var url = 'google sheet url here'
var sh = 'sheet1'<!-- current google sheet name here -->
var folderId = 'google drive folder id here'
function processForm(formdata){
var superscript = SuperScript.initSuper(url,sh)
var formObject = {}
formdata.forEach(element => formObject[element.name] = element.value),
formdata.forEach(element => formObject[element.message] = element.value)
formdata.forEach(element => formObject[element.email] = element.value)
formdata.forEach(element => formObject[element.phone] = element.value)
var file = superscript.uploadFile(folderId,formObject.myfile.data,formObject.myfilename)
var ss= SpreadsheetApp.openByUrl(url);
var ws=ss.getSheets()[0]
ws.appendRow([
new Date(),
formObject.name,
"'"+formObject.message,
formObject.email,
formObject.phone,
file.getUrl()
]);
};
index.html
<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<div class="container py-5">
<div class="row">
<div class="col-lg-5 col-md-8 mx-auto shadow border bg-white p-4 rounded">
<nav class="navbar navbar-dark bg-primary">
<a class="navbar-brand" href="#" fw-bold mb-3>WRITE YOUR QUERY / Message</a>
</nav>
<br>
<form id="myForm" onsubmit="handleFormSubmit()">
<div id="form_alerts"></div>
<div class="form-group mb-3">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter your Name here|" name="name"required>
</div>
<div class="form-group mb-3">
<label for="email" >Email</label>
<input type="email" class="form-control" id="email"
placeholder="Enter your email address here|" name="email" required>
</div>
<div class="form-group mb-3">
<label for="phone">phone number</label><br><br>
<input type="tel" id="phone" class="form-control" name="phone" placeholder="Enter your phone number here with country code." pattern="[+]{1}[0-9]{2}[0-9]{10}" required><br><br>
<small>Format: +919234567898</small><br><br>
</div>
<div class="form-group mb-3">
<label for="message">Message</label>
<textarea class="form-control" id="message" placeholder="Write your message here|" name="message" required ></textarea>
</div>
<div class="form-group mb-3">
<label for="uploadFile">Upload File</label>
<input type="file" class="form-control" File="file" id="file">
</div>
<button type="submit" class= "btn btn-primary btn-block">SEND</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function (event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit() {
var formdata = $('#myForm').serializeArray()
formdata.push({
name: 'myfile',
value: myfile
})
google.script.run.withSuccessHandler(success).processForm(formdata);
}
function success(){
document.getElementById("myForm").reset()
Swal.fire({
position: 'center',
icon: 'success',
title: 'sended sucessfully be ready we will contact you shortly',
showConfirmButton: true,
})
}
var myfile ={},file, reader = new FileReader();
reader.onloadend = function(e) {
myfile.data = e.target.result
myfile.name = file.name
console.log(myfile)
};
$('#file').change(function(){
file = $('#file')[0].files[0]
reader.readAsDataURL(file);
})
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="sweetalert2.all.min.js"></script>
</body>
</html>
虽然我不确定是否能正确理解你的预期结果,但是按如下方式修改你的脚本怎么样?
在此修改中,您的 Google Apps 脚本函数
processForm(formdata)
已修改。
function processForm(formdata) {
var superscript = SuperScript.initSuper(url, sh);
var formObject = {};
formdata.forEach(element => formObject[element.name] = element.value);
formdata.forEach(element => formObject[element.message] = element.value);
formdata.forEach(element => formObject[element.email] = element.value);
formdata.forEach(element => formObject[element.phone] = element.value);
var f = formdata.find(({ name }) => name == "myfile");
var file = (f && f.value?.name && f.value?.data) ? superscript.uploadFile(folderId, formObject.myfile.data, formObject.myfilename) : "";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheets()[0];
ws.appendRow([
new Date(),
formObject.name,
"'" + formObject.message,
formObject.email,
formObject.phone,
file && file.getUrl()
]);
// About your request, if you want to send an email, how about using the following script. But, in this case, please set your subject and email body.
MailApp.sendEmail({ to: formObject.email, subject: "sample subject", body: "sample body" });
}
无论是否上传文件,此修改都适用。
关于您的第二个请求
i tryed to add feature like auto sending email to receiver after user submit form successfully. but i unable to code that part,if someone know how to do that is most welcome to add this auto email feature.
,如果您想发送电子邮件,请使用函数中的最后一行processForm
。但是,在这种情况下,请设置您的主题和电子邮件正文。这样,当单击按钮时,一封电子邮件就会发送到输入的电子邮件地址。
在您的显示脚本中,似乎使用了Web Apps。当您修改Web Apps的Google Apps脚本时,请将部署修改为新版本。这样,修改后的脚本就会反映在Web Apps中。请注意这一点。
您可以在我的报告“在不更改 Web 应用程序 URL 的情况下重新部署 Web 应用程序(作者:我)”中查看详细信息。