首页 > 解决方案 > 谷歌应用 json 数据从 code.gs 到 html 下拉列表

问题描述

我正在创建一个谷歌应用程序脚本,并试图将 json 数据从 code.gs 放到 html 文件下拉列表中。我真的不知道这是如何通过对 JS 和谷歌自己的东西没有那么丰富的经验来完成的。继承人的代码:

function PopulateDropDownList() {

var url = 'url for the api call'

var res = UrlFetchApp.fetch(url, {'api stuff here, it works i have tested it'}})

var json = res.getContentText()
var txt = JSON.parse(json)

people = txt.data.map(function (a) { 
  return [a.firstName, a.lastName]; 
})

Logger.log(people)
return people
       
    }

问题是,如何将“人员”列表添加到 html 下拉选择中?我知道它与脚本标签有关,但我真的不知道该怎么做。我也尝试过 goolge.script.run.myFunction 但我不知道如何从那里取得进展

编辑:

HTML 文件

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <select id="droplist">
      </select>
      <script>
      (function () {
        google.script.run.withSuccessHandler(
          function(people) {
            var select = document.getElementById("droplist");
            for( var dude of people) {
              var option = document.createElement("option");
              // option.text = dude.firstName + " " + dude.lastName;
              option.text = dude[0] + " " + dude[1];
              select.add(option);
            }
          }
        ).get_people();
      }());
    </script>
  </body>
</html>

代码.gs:

function getPeople() {
 /*json stuff here*/
    var json = res.getContentText()
    var txt = JSON.parse(json)

    var people = txt.data.map(function (a) { 
      return [a.firstName, a.lastName]
      })
     Logger.log(people)
     return people
}

function showDialog() {
  var html = HtmlService.createTemplateFromFile("Page").evaluate();
  // return html;
  SpreadsheetApp.getUi().showModalDialog(html, "List");
}

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('choose person')
      .addItem('search', 'showDialog')
      .addToUi();
}

标签: javascripthtmljsongoogle-apps-script

解决方案


我猜您正在使用HtmlService. 如果是这样,您可以使用模板来动态生成 HTML。在您的项目中创建一个新的 HTML 文件并使用scriptlet生成您想要的 HTML。

这是一个带有select标签的简单示例:

Code.gs

function doGet(e) {
  const template = HtmlService.createTemplateFromFile('Template')
  template.people = getPeople()
  return template.evaluate()
}

function getPeople() {
  const url = 'url for the api call'
  const res = UrlFetchApp.fetch(url, {'api stuff here, it works i have tested it'}})
  const txt = JSON.parse(res.getContentText())
  
  return txt.data.map(function (a) { 
    return [a.firstName, a.lastName]
  })
}

Template.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <select>
      <? for (let person of people) { ?>
        <option><?= person[1] ?>, <?= person[0] ?></option>
      <? } ?>
    </select>
  </body>
</html>

参考


推荐阅读