使用Google表格脚本编辑器将数据提交到不同的标签

时间:2020-02-17 14:03:23

标签: javascript google-apps-script google-sheets google-apps

在电子表格脚本编辑器中,我具有以下代码:

Code.gs

function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

function doPost1(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var checkForm = ss.getSheetByName("checkForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("ID");
    var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
    if (allEvents.length > 0) {
    return HtmlService.createTemplateFromFile('calendarAgenda.html')
    }else {
    return HtmlService.createTemplateFromFile('bookingForm.html')
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function doPost2(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bookForm = ss.getSheetByName("bookForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);    

    return ContentService
    .createTextOutput(JSON.stringify('Successfully received. Thank you!'))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

checkForm.html

<!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" action="ScriptURL" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost1(e);
}
</script>
</body>
</html>

bookingForm.html

<!DOCTYPE html>
<body>
<form name="class1Booking" id="class1Booking" action="ScriptURL" target="_self" method="POST">
<inputs> ..
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost2(e);
}
</script>
</body>
</html>

goGet函数返回“ checkForm.html”页面,提交该页面时应运行doPost1函数以将数据发送至电子表格中的“ checkForm”选项卡,然后返回提交时的第二个页面“ bookingForm.html”应该运行doPost2函数将数据发送到“ bookForm”标签,然后返回特定的文本输出

提交检查表时,出现错误“找不到脚本功能:doPost”,我认为google.script.run可能存在一些问题,我尝试几次修改都没有运气。任何帮助和感谢

2 个答案:

答案 0 :(得分:0)

忘记doPost()。尝试这样的事情。

HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <style>#msg{display:none;}</style>
  </head>
  <body>
    <form>
      <!--><inputs type="text" name="name1">--> 
      <button type="button"  value="Submit" onclick="processForm(this.parentNode);" />
      </form>
 <div id="msg"></div>
 <script>
   $(function(){
     //You can get stuff from the server after the dom has loaded.  I know it takes some time but it's a simple way to intialize.  Personally for my own sutff Id rather do this that use templated html
   });

  function processFormC(form) {
    //input validation
    google.script.run
    .withSuccessHandler(function(obj){
      $('#msg').css("display","block");
      $('#msg').html(obj.msg);
    })
    .processFormS(form);
  }
</script>
  </body>
</html>

GS:

function processFormS(obj) {
  //obj.name1...
  return {msg:'Got it.'}
}

function doGet() {
    return HtmlService.createHtmlOutputFromFile('whatever file name')
}

我个人更喜欢将所有javascript和css放在同一个文件中,因为以后更容易找到它。是的,我知道它会变大,但是再次由我选择,不必由您选择。

答案 1 :(得分:0)

您没有正确使用google.script.run函数,如documentation中所述,您只能返回以下类型的值:

数字,布尔值,字符串或null以及JavaScript对象和 由基元,对象和数组组成的数组。

在您的情况下,您尝试返回一个不允许的textOutput对象,该类适用于Web Apps函数(doGet(e)或doPost(e))。

在有关[客户端到服务器通信](https://developers.google.com/apps-script/guides/html/communication)的文档中,介绍了如何使用google.script.run。这是一个适用于您的案例的示例,因此您可以更好地了解其工作原理:

checkForm.html

<!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button onclick="postData(this.parentNode)">Check</button>
</form>
<script>
//It’s run when form button is clicked 
function postData(form) {
   //Calls doSomething function in code.gs with form parameter
  google.script.run.withSuccessHandler(handlerFunction).doSomething(form);
}

//Handles the response from doSomething function
function handlerFunction(responseData) {
  //Logs ‘It worked!’ in developer console
  console.log(responseData);
}
</script>
</body>
</html>

code.gs

//Web App function
function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

//Apps script function to receive form object and return response
function doSomething(form) {
//Do something
  return ‘It worked!’;
}

Apps Script的Web Apps设计为单页应用程序(一个HTML页面),而不是多页应用程序,尽管您可以从中获得不同的解决方法示例,以实现多页行为:

[1] Linking to another HTML page in Google Apps Script

[2] https://sites.google.com/corp/view/googlappsscript/recent-scripts/multiple-page-webapp-example