0

スプレッドシートから情報を取り出し,Google サイトのページ上に表示したいと思っているのですが難航しています. GAS で UI サービスがなくなるにあたって,今までのものを書き換えようとしていきなり躓いています.以下のコードの間違いを指摘していただけたら助かります.当方初心者ですごく基本的なことなのかもしれませんがよろしくお願いします.

Code.gs

function doGet() {
      return HtmlService.createHtmlOutputFromFile('index')
          .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function test(myform) {
  var name = SpreadsheetApp.openById("スプレッドシート名")
     .getSheetByName("シート名").getRange(2, 1).getValue();
  myform.tbox.value = name;
}

index.html

<html>
<form name="myForm">
  <input type="text" name="tbox"/><br>
  <input type="button" value="表示"
      onClick="google.script.run.test(this.form)" />
</form>
</html>

2 件の回答 2

0

上記のコードをが何をしたいかによって回答が変わりますが、
最低限そのまま動くように直すのであれば以下のようになります。

Code.gs

function doGet() {
      return HtmlService.createHtmlOutputFromFile('index')
          .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function test(myform) {
  //↑test関数の引数myformはこの関数の入力値として使います。
  //例えばtextboxに入れた値をSpreadsheetに反映したい場合などです。
  //今回の処理では値をSpreadsheetから取得しているのみなので入力値は使いませんので必要ないはずで、なくても問題ないはずです。

  var name = SpreadsheetApp.openById("スプレッドシート名")
     .getSheetByName("シート名").getRange(2, 1).getValue();
  // myform.tbox.value = name;
  return {data: name}; //html側に返したいデータを返却します。 
  //上記が後述するwithSuccessHandlerコールバックの引数になります。
}

index.html

<html>
<form name="myForm">
  <input type="text" name="tbox"/><br>
  <input type="button" value="表示"
      onClick="onClick(this.parentNode)" /> <!-- ←の部分が長くなるので↓の<script>に移動しました。-->
</form>
<script>
function onClick(form) {
  google.script.run
      .withSuccessHandler(function(result) {
          //withSuccessHandlerはCode.gs内の関数の戻り値を処理します。
          //今回の処理ではCode.gsのtestの戻り値{data: name}が引数resultに渡されます。
          document.getElementsByName("tbox")[0].value = result.data; 
      })
      .test(form); //form要素を渡すとform要素内にあるinput要素の値がCode.gs側の関数の引数として使えます。 またハマったら別の質問で聞いて下さい。
}
</script>
</html>
0

既にベストアンサーが出てはいますが、こんなやり方もあります。

GAS側コード:

function doGet() {
  var output = HtmlService.createTemplateFromFile('index.html');
  var html = output.evaluate();
  return html;
}

HTML側コード:

<script>
  var testman = <?!=JSON.stringify(SpreadsheetApp.openById("1SIeCloowtUiUc33T9prkKtbnAfpQ0w52nRFrxlHGsFU").getSheetByName("kinoko").getRange("A2:A").getValues());?>

  function onClick(){
    document.getElementById("tbox").value = testman[0];
  }
</script>
<form name="myForm">
<input type="text" id="tbox"/><br>
<input type="button" value="表示" onClick="onClick()" />
</form>

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。