我应该在哪里调用getUserProperties函数?

时间:2018-07-25 03:26:58

标签: javascript jquery jquery-ui google-apps-script

我正在尝试创建一个按钮,单击该按钮可以“保存”已连接可排序对象中多个列表的位置。我希望脚本能够在刷新页面时保留每个列表项的最新位置(即,如果列表1以A,B,C开头,我将其更改为B,A,C并刷新页,它保持为B,A,C。)。

我正在尝试通过从html文档(作为Web应用程序发布)创建数组,使用getUserProperities函数将其保存,然后在下次打开Web应用程序时将其返回来实现此目的。

我能够记录职位,但没有问题,但是我很难弄清楚在何处运行getUserProperities函数,或者可能要处理的其他问题。

在Web应用程序的控制台中,出现此错误Uncaught TypeError: Cannot read property 'getUserProperties' of undefined at saveList (userCodeAppPanel:4) at HTMLButtonElement.onclick (userCodeAppPanel:1)

我应该在哪里调用getUserProperties函数?来自code.gs还是index.html?我一直在研究HERE提供的示例。

我的代码中来自index.html的相关部分如下。

<script>
  $( function() {
    $( "#myList, #flight1a, #flight1b, #flight2a, #flight2b, #flight3a, #flight3b, #sortable2" ).sortable({
      connectWith: ".connectedSortable",
      update: function(event, ui) {
        var changedList = this.id;
        var order = $(this).sortable('toArray');
        var positions = order.join(';');

        console.log({
        id: changedList,
        positions: positions

        });
      }
    })
   });

</script>

 <script>
    function saveList() {

      google.script.run.PropertiesService.getUserProperties().setProperty('myProperty', JSON.stringify(positions));

      var returnedObj = PropertiesService.getUserProperties("myProperty");
          returnedObj = JSON.parse(returnedObj);
      }  
</script>

  </head>

  <body>

<button onclick="saveList()">Click me</button>

2 个答案:

答案 0 :(得分:3)

google.script.run可用于调用服务器端函数,而不直接调用属性服务。

有关更多详细信息,请参见https://developers.google.com/apps-script/guides/html/reference/run

答案 1 :(得分:3)

属性服务只能通过Google Apps脚本访问,因此必须在您的*.gs文件之一中调用。要执行服务器端功能,您需要使用google.script.run(还有一个guide available)。

例如,在您的code.gs文件中添加以下功能:

function savePositions(propertyName, value) {
  PropertiesService.getUserProperties().setProperty(propertyName, value);
}

然后,在您的index.html文件中,将saveList()修改为:

function saveList() {
  google.script.run.savePositions("myProperty", JSON.stringify(positions));
}