How to return an array (Google apps script) to a H

2019-06-04 13:07发布

I would like to return some array I made in my code.gs to my HTML sidebar and use it to fill a select, I have this so far:

Lets say I would like to use "['this', 'part', 'of', 'the', 'array', 'for', 'the', 'select']" for the html select:

code.gs

function ExampleArray(){
var tempArr = [['this', 'part', 'of', 'the', 'array', 'for', 'the', 'select'], []];
return tempArr;
}

So that is the array, I need that array to populate a html select object so I need a HTML page as well. This is my HTML code for the select:

<script> 
google.script.run.ExampleArray();
</script>    
<div>
         <?
            var data    =  //the array from the code.gs
         ?>
       <div class="two">
       <select id="Select1">
       <? for (var i = 0; i < data.length; ++i) { ?>
       <option><?!= data[i] ?></option>
       <? } ?>
       </select>
       </div>

How can I achieve this? :)

1条回答
倾城 Initia
2楼-- · 2019-06-04 13:34

You can either use successHandler or just call the script, as such:

google.script.run.withSuccessHandler(onSuccess).ExampleArray();

function onSuccess( values ){
  $.each(values, function(key, value) {   
     $('#Select1')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
  });
}

or

<?
  var data = ExampleArray();
?>

I always use the first method for my codes, I think it has a better control over the application. But that's just an opinion.

查看更多
登录 后发表回答