簡體   English   中英

使用Apps腳本處理HtmlOutput中的html內容

[英]Using Apps Script to manipulate the html content in HtmlOutput

我正在使用Apps Script並嘗試在Google Sheet中創建一個Sidebar ,以顯示將內容轉換為JSON的結果。

這是頁面Sidebar的html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <!-- The CSS package above applies Google styling to buttons and other elements. -->
    <style>
      .width-100 {
        width: 100%;
        height: 100%
      }
    </style>
  </head>
  <body>
    <div class="sidebar branding-below">
      <form>
        <div class="block form-group">
          <label for="json"><b>JSON</b></label>
          <textarea class="width-100" id="json" name="json" rows="10"></textarea>
        </div>
      </form>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
  </body>
</html>

我之前已經創建了所需的JSON ,現在正嘗試使用此方法使用創建的JSON設置textarea的內容:

function displayText_(text) {
  var html = HtmlService.createHtmlOutputFromFile('Sidebar')
  .setTitle('JSON Results');
  var contents = html.getContent();
  contents.getElementById('json').setText(text);
  html.setContent(contents);
  SpreadsheetApp.getUi().showSidebar(html);
}

這是用於答案的樣本JSON字符串:

var jsonString = {"someKey":"someValue","anotherKey":"anotherValue"}

我嘗試通過連接到htmlcontents來使用getElementById (我當前的方法)。 什么都不會產生預期的結果。 我猜這很簡單,但是不知道如何從Apps Script操縱html。

我很確定我可以在Apps Script創建整個html內容並替換其中的內容,但這是一個hack,不容易維護。

有沒有更簡單的方法可以做到這一點?

據我了解,您要實現的目標是在客戶端從服務器端注入內容。 函數displayText_是服務器端函數。
如果是這樣,您可以將服務器端功能更改為看起來像這樣的功能:(代替簡單的客戶端文件,我們將使用模板文件)

function displayText_(text) {
  var htmlTemplate = HtmlService.createTemplateFromFile('Sidebar');
  htmlTemplate.json = text;
  var html = htmlTemplate.evaluate().setTitle('JSON Results');
  SpreadsheetApp.getUi().showSidebar(html);
}

然后在客戶端,您需要進行更改

<textarea class="width-100" id="json" name="json" rows="10"></textarea>

對於

  <textarea class="width-100" id="json" name="json" rows="10"><?!=json?></textarea>

如果您想進行動態更改,則應在此處查看客戶端/服務器的通信過程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM