将值从侧边栏中的html表单传递给Google脚本 [英] Pass value from an html form in sidebar to google script

查看:48
本文介绍了将值从侧边栏中的html表单传递给Google脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这方面遇到困难...阅读了文档,但我无法做到.

I have difficulties in this... I read the documentation but I'm not able to do it.

我想在Google文档的边栏中创建一个小的html表单.此表单将从联系人"中拉出联系人组",以便用户可以选择一个并将t传递给我的脚本.

I want to create a little html form in a sidebar of a Google Document. This form will pull the Contacts Group from Contacts so the user can chose one and pass t to my script.

这就是我所做的:

Page.html

Page.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />
  </body>
</html>

menu.gs

function doGet() {
  return HtmlService
      .createTemplateFromFile('Page')
      .evaluate();
}

function onOpen() {
  DocumentApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();

}

function showSidebar() {

  var html = HtmlService.createHtmlOutputFromFile('Page')
      .setTitle('Chose the Contact Group')
      .setWidth(300);

  var groups = ContactsApp.getContactGroups();

  // add this to the html file Page.html
  html.append ('<form onsubmit="google.script.run.myFunction(formObject)">'+
               '<select>');

  for (var i = 0; i < groups.length; i++) {
    html.append('<option name="chosenGroup" value="' + groups[i].getName() + '">' + groups[i].getName() + '</option>');
  }

  html.append('</select><input type="submit">');

  //this is commented because I was testing it
  //html.append("<script>function handleFormSubmit(formObject) { google.script.run.myFunction(formObject); } </script>");

    DocumentApp.getUi() // Or DocumentApp or FormApp.
      .showSidebar(html);

}  

Code.gs

myFunction (formObject) {

Logger.log(formObject.chosenGroup);

}

当我单击提交"按钮时,将打开一个新的空白页面,其网址如下:

When I click on the submit button a new blank page is opened with a url like:

https://n-wuewuewuee98efgdsf98769s8d76f9s76df-0lu-script-google.UserUserPanel.?

推荐答案

发生这种情况是因为'form'标签的'action'属性.提交表单时,浏览器将重定向到'action'属性中指定的路由.通常,此URL模式映射到接收表单发布的数据的服务器上的代码.

That happens because of the 'action' attribute of the 'form' tag. When you submit a form, the browser is redirected to the route specified in the 'action' attribute. Usually, this URL pattern is mapped to the code on the server that receives data posted by the form.

您的代码中还有其他问题应首先解决:

There are other issues in your code that should be addressed first:

1)仅当将脚本部署为Web应用程序时才需要doGet()函数.当您在浏览器中打开该应用程序的URL时,即执行doGet()中的代码,即向该应用程序发送"GET"请求.您的脚本是文档绑定的,因此不需要doGet()

1) The doGet() function is needed only when you deploy the script as a web app. The code in doGet() executes when you open that app's URL in a browser, i.e. send a 'GET' request to the app. Your script is document-bound, so no need for doGet()

2)业务逻辑的各个方面.showSideBar()必须完全执行应做的事情,即显示侧边栏.getContactGroups()必须返回联系人组的数组,等等.

2) Separate aspects of your business logic. showSideBar() must do exactly what it's supposed to do, namely, show the sidebar. getContactGroups() must return the array of contact groups, etc.

3)请记住,您可以将变量传递到HTML页面,并使用模板HTML动态创建UI.无需逐行追加! https://developers.google.com/apps-script/guides/html/模板

3) Remember, you can pass variables to HTML pages and create UI dynamically using templated HTML. No need for appending line by line! https://developers.google.com/apps-script/guides/html/templates

4)最后,使用jQuery可以轻松解决重定向到另一个页面的问题.

4) Finally, the redirect to another page can be easily solved by using jQuery.

请参见下面的示例代码.我的脚本绑定了电子表格,因此您要做的就是用DocumentApp替换SpreadsheetApp.

See sample code below. My script was spreadsheet-bound, so all you have to do is replace SpreadsheetApp with DocumentApp.

服务器代码(main.gs)

Server code (main.gs)

function onOpen(){

var ui = SpreadsheetApp.getUi();

ui.createMenu('Menu')
  .addItem('Show sidebar', 'showSidebar')
  .addToUi();


}


function showSidebar() {

var ui = SpreadsheetApp.getUi();
var template = HtmlService.createTemplateFromFile('sidebar');

template.contactGroups = getContactGroups(); //adding contactGroups as a property of the template object. 

ui.showSidebar(template.evaluate()); //Calling evaluate() executes the inline JS code in sidebar.html, populating the dropdown list


}

function getContactGroups(){

try {

var contactGroups = ContactsApp.getContactGroups();

} catch(error) {

Logger.log(error);

}

return contactGroups;

}

function processFormResponse(formObject){


Logger.log(formObject.chosenGroup);



}

这是sidebar.html.请注意html文件中内联代码的特殊语法.调用e.preventDefault()负责重定向到另一个页面.由于我们将contactGroups作为属性添加到模板对象,因此在调用validate()时,此变量将可用.下面的内联代码将使用组名动态填充下拉列表.

And here's sidebar.html. Note the special syntax for inline code within html files. Calling e.preventDefault() takes care of the redirect to another page. Since we are adding contactGroups as a property to the template object, this variable will be available when evaluate() is called. The inline code below will dynamically populate the dropdown list with group names.

<!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
        Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />

        <form>
        <select name="chosenGroup">

        <? for (var i=0; i < contactGroups.length; i++) { ?>

        <option value="<?= contactGroups[i].getName()?>"><?= contactGroups[i].getName()?></option>


        <?}?>
        </select>
        <input type="submit" value="Submit">
        </form>



       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
       <script>

        $(document).ready(function(){

              $('form').submit(function(e){

                e.preventDefault();

                google.script.run.processFormResponse(this);


              });


        });

       </script>


      </body>
    </html>

更新

关于jQuery没什么特别的.它是一个JS库,旨在简化DOM树的导航,但它基于浏览器中的DOM API构建.长话短说,您不需要jQuery即可达到此结果.1)为您的表单"标签分配一个唯一的ID,例如

There's nothing special about jQuery. It's a JS library designed to make navigating the DOM tree a bit easier, but it's built on top of the same DOM API in your browser. Long story short, you don't need jQuery to achieve this result. 1) Assign a unique id to your 'form' tag, e.g.

<form id="form">

2)创建一个将事件侦听器添加到侦听"submit"事件的表单的函数.第二个参数是事件处理函数.使用单击"而不是提交"将迫使您通过按ID引用文本字段并获取用户输入来手动创建表单对象.

2) Create a function that adds an event listener to the form that listens to the 'submit' event. The 2nd argument is the event handler function. Using 'click' instead of 'submit' will force you to create the form object manually by referencing text fields by id and getting user input.

   <script>
      function addEventListeners() {

       document.getElementById('form').addEventListener('submit', function(e){

       e.preventDefault();
       google.script.run.processFormResponse(this);


       });



       }
      </script>

最后,在加载时调用此函数.

Finally, call this function on load.

<body onLoad="addEventListeners()">

我上一个示例中的jQuery代码做了完全相同的事情,但是可读性更高且易于维护.

The jQuery code in my previous example did exactly the same thing, but was much more readable and easy to maintain.

这篇关于将值从侧边栏中的html表单传递给Google脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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