Google apps脚本不会记录提交内容 [英] Google apps Script won't record submissions

查看:89
本文介绍了Google apps脚本不会记录提交内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我从研究和一些我自己的补充中整理出来的一个程序,我遇到了很多问题。 record_submission 函数无法正常工作。每次我与提交姓名的人一起测试时,它都不会正确记录影响下一个功能的信息,即我写的通知功能,当有人提交回复时,会自动给我发送电子邮件。希望得到一些帮助。

随附的是Google电子表格中的图片,我希望在有人提交回复时提供更新,以及网站人员将提交信息的面部从。记录功能应该这样做。它给我一个错误,指出这个变量没有正确分配,或者是某种类型的东西,而且通知邮件也无法正常工作。







这是整个JavaScript代码:

  // *此函数处理来自Web浏览器的获取请求* / 
函数doGet(e)
{
//返回form.html作为响应返回
HtmlService.createHtmlOutputFromFile('form html的');
}

//将输入表单的所有信息记录到Google表格中。
函数record_submission(表单)
{
Logger.log(form);
var ss = SpreadsheetApp.openById(1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8);
var sheet = ss.getSheets()[0]; //假设第一个工作表收集到响应

//用时间戳创建一行数据+发布的响应
var row = [new Date(),//时间戳
form.last_name [0],//姓氏
]; //确保我们是向电子表格添加行的唯一人员
var lock = LockService.getPublicLock(); //等待30秒以完成其他进程。
var locked = lock.tryLock(30000);
if(locked)
{
//保存对电子表格的响应
var rowNum = sheet.getLastRow()+ 1;
sheet.getRange(rowNum,1,1,row.length).setValues([row]);

//释放锁以便其他进程可以继续。
lock.releaseLock();
var result =记录的响应:\ n
+ row.join('\\\
');
}
else
{
//获取锁定失败
result =
系统繁忙,请重试。
}
//以纯文本形式报告POST的结果
返回ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}

//发送电子邮件给自己,当有人提交时通知您。
函数通知(姓氏,赋值名称)
{
var subject =New Submission; MailApp.sendEmail(* my email*@gmail.com,
subject,'从'+ last_name +'收到的
赋值的新提交:'+ assignment_name);
}

/ *这个函数会在提交按钮被
点击时处理表单* /
function uploadFiles(form)
{
试试
{
notification('test','test'); //检索对Google云端硬盘文件夹的引用
var folder_name =Test_Folder
var folder =
DriveApp.getFolderById(0By69oDzO6OluTm9KNGVuaUZZdE0);

//如果文件夹不存在,创建一个新文件夹
if(!folder)
{
folder = folder.createFolder(folder_name);
}

//获取通过表单上传的文件blob
var blob = form.myFile;
var file = folder.createFile(blob);

//将文件描述设置为上传者的名称
file.setDescription(Uploaded by+ form.LastName);

//将文件名设置为上传者的名称
file.setName(form.LastName +_+ form.AssignmentName);

//此函数应该将提交的信息存储到Google Sheet

record_submission(表单)中;

//此函数应在提交
通知(form.LastName,form.AssignmentName)时通知您;

//在Google Drive
返回File uploaded successfully文件后,返回文件的下载网址+ file.getUr1();
}
catch(error)
{
//如果有错误,显示错误消息返回
error.toString();


$ / code $ / pre

这是整个HTML代码







文件上传

 <! - 使用者输入 - > 
< h4>名字< / h4>
< input type =textname =FirstNameplaceholder =输入您的名字..>


< h4>姓氏< / h4>
< input type =textname =LastNameplaceholder =Your last name ...>

< h4>作业名称< / h4>
< input type =textname =Courseplaceholder =Course number>

<! - 文件上传 - >
< h4>上传< / h4>
< input type =fileid =filename =myFilestyle =display:block; margin:20px; value =myFile>

<! - - 提交按钮 - >
< input type =submitvalue =Submit
onclick =this.value ='上传..';
google.script.run.withsuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;>
< / form> < div id =output> < / DIV> <脚本>
函数fileUploaded(status){
document.getElementById('myForm')。style.display ='none';
document.getElementById('output')。innerHTML = status;
}


/ *检查用户的名字输入是否为空。
如果为空,提醒用户填写他/她的名字* /


< / script>

< style>
input {display:block; margin:20px; }
< / style>

< / body> < / HTML>



解决方案

你的'input'标签没有被包装在'form'标签中,所以传递给'onclick'函数的参数实际上可能是整个< body>标签。您的输入嵌套在< form>标签内吗?如果不是,那么this.parentNode将是HTML文档的整个主体。

我整理了一个说明整个过程的快速示例。在客户端,我们正在侦听表单提交事件。一旦事件触发,我们通过google.script.run调用服务器端函数,并将表单对象作为参数传递给该函数。



Code.gs p>

  function onOpen(){

var ui = SpreadsheetApp.getUi();

ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('siderbar'));



$ b函数logFormObject(form){

Logger.log(form); //通过按Ctrl +返回
var ss = SpreadsheetApp.getActiveSpreadsheet();来检查日志。
var sheet = ss.getSheets()[0]; //获取电子表格中的第一张图片
sheet.appendRow([form.name,form.lastName,form.age]); //从表单对象创建行内容数组并将其传递给appendRow()方法

$ b}

HTML

 <!DOCTYPE html> 
< html>
< head>
< base target =_ top>
< / head>
< body>
< form id =myForm>

名称< br>
< input name =name/> <峰; br>
姓氏:< br>
< input name =lastName/> <峰; br>
年龄:< br>
< input name =age/> <峰; br>

< input type =submitvalue =send>

< / form>
< script>

window.onload = function(){

var form = document.getElementById('myForm');
form.addEventListener('submit',function(event){

event.preventDefault(); //防止重定向到另一页
google.script.run.logFormObject this); //在Code.gs中调用服务器函数

});


}

< / script>
< / body>
< / html>


Below is a program that I put together, from research and some of my own adding, and I'm having many issues with it. The record_submission function isn't working properly. Every time I test with someone submitting their name, it won't properly record the information which then effects the next function, the notification function which I wrote to automatically send me an email once someone submits a response. Would appreciate some help.

Attached are the images of the Google spreadsheet that I want updated whenever someone submits a response as well as the face of the website people will be submitting information from. The record function is supposed to do that. It's giving me a error saying that the variable isn't properly assigned or something of the sort and the notification email doesn't work properly either.

This is the whole JavaScript code:

 //* This function handles the get request from the web browsers */
 function doGet(e)
 { 
     //return form.html as the response return
     HtmlService.createHtmlOutputFromFile('form.html');
 }

 // Record all the information entered into the form into a Google Sheet.
 function record_submission(form)
 {
     Logger.log(form);
     var ss = SpreadsheetApp.openById("1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8");
     var sheet = ss.getSheets()[0]; // Assume first sheet collects responses

     // Build a row of data with timestamp + posted response
     var row = [ new Date(), // Timestamp 
                 form.last_name[0], // last name
               ]; // Make sure we are the only people adding rows to the spreadsheet
     var lock = LockService.getPublicLock(); // Wait for up to 30 seconds for other processes to finish. 
     var locked = lock.tryLock(30000);
     if (locked)
     {
         // Save response to spreadsheet 
         var rowNum = sheet.getLastRow() + 1;
        sheet.getRange(rowNum, 1, 1, row.length).setValues([row]);

        // Release the lock so that other processes can continue.
        lock.releaseLock(); 
        var result = "Response Recorded: \n 
 "+row.join('\n  ');
    }
    else
    {
        // Failed to get lock
        result =
 "System busy, please try again.";
    }
    // Report result of POST, in plain text
    return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}

 // Send an email to yourself notifying you when someone made a submission.
function notification(last_name, assignment_name)
{
   var subject = "New Submission"; MailApp.sendEmail("*my email*@gmail.com",
 subject, 'New submission received from ' + last_name + ' for the
 assignment: ' + assignment_name );
}

 /* This function will process the form when the submit button is
 clicked */
 function uploadFiles(form)
 {
     try
     {
         notification('test','test'); //Retrieve a reference to the folder in Google Drive 
         var folder_name = "Test_Folder"
         var folder =
 DriveApp.getFolderById("0By69oDzO6OluTm9KNGVuaUZZdE0");

         // Create a new folder if the folder does not exist 
         if (!folder)
         {
             folder = folder.createFolder(folder_name);
         }

         //Get the file uploaded through the form as a blob
         var blob = form.myFile;
         var file = folder.createFile(blob);

         //Set the file description as the name of the uploader
         file.setDescription("Uploaded by " + form.LastName);     

         //Set the file name as the name of the uploader
         file.setName(form.LastName + "_" + form.AssignmentName); 

         //This function should store the information of the submission to a Google Sheet

         record_submission(form);

         //This function should notify you when there has been a submission 
         notification(form.LastName, form.AssignmentName);

         // Return the download URL of the file once its on Google Drive
         return "File uploaded successfully " + file.getUr1();
   }
   catch(error)
   { 
       // If there's an error, show the error mesage   return
       error.toString();
   }
}

This is the whole HTML code

File Upload

<!--User inputs --> 
<h4>First name</h4> 
<input type="text" name="FirstName" placeholder = "Type your first name.." > 


<h4> Last Name </h4> 
<input type="text" name = "LastName" placeholder="Your last name...">

<h4> Assignment Name </h4>
<input type="text" name="Course" placeholder="Course number"> 

<!--File upload--> 
<h4>Upload</h4> 
<input type="file" id="file" name="myFile" style="display:block; margin: 20px;" value = "myFile"> 

<!-- Submit button --> 
<input type="submit" value="Submit" 
    onclick= "this.value='Uploading..';
         google.script.run.withsuccessHandler(fileUploaded)
         .uploadFiles(this.parentNode);
         return false;">
           </form>    <div id="output">  </div>     <script>
 function fileUploaded(status) { 
     document.getElementById('myForm').style.display = 'none'; 
     document.getElementById('output').innerHTML = status;
     }


     /*check to see if the user's first name input is empty. 
     If it is empty alert the user to fill in his/her first name */ 


     </script>

     <style> 
          input {display:block; margin: 20px; }
          </style>

 </body> </html>

解决方案

I see that your 'input' tags are not wrapped in a 'form' tag, so what gets passed to the 'onclick' function as parameter might actually be the entire <body> tag. Are your inputs nested inside the <form> tag? If not, then this.parentNode would be the entire body of the HTML document.

I put together the quick example illustrating the entire process. On the client side, we are listening for the form submit event. Once the event fires, we call the server-side function via google.script.run and pass the form object to that function as an argument.

Code.gs

function onOpen(){

var ui = SpreadsheetApp.getUi();

ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
  .setTitle('siderbar'));

}


function logFormObject(form){

Logger.log(form); //check the logs by pressing Ctrl + Return
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // get the 1st sheet in the spreadsheet
sheet.appendRow([form.name, form.lastName, form.age]); //create row contents array from the form object and pass it to the appendRow() method


}

HTML

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form id="myForm">

      Name <br>  
      <input name="name" /> <br>
      Last Name: <br>  
      <input name="lastName" /> <br>
      Age: <br>  
      <input name="age" /> <br>

      <input type="submit" value="send">

    </form>
    <script>

      window.onload = function(){

        var form = document.getElementById('myForm');
        form.addEventListener('submit', function(event) {

          event.preventDefault(); //prevents redirect to another page
          google.script.run.logFormObject(this); // calling the server function in Code.gs

        }); 


      }

    </script>
  </body>
</html>

这篇关于Google apps脚本不会记录提交内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆