4

我有一个相当基本的电子表格,它使用一些 Google 脚本来完成各种任务。我试图为最终用户清理界面,并决定实现 Google Picker。最初,用户必须手动将 CSV 导入电子表格。这里的新目标是通过 Google Picker 选择 CSV,上传,导入,然后删除。我已经有所有代码可以导入并删除它。我刚刚为选择器编写了代码,它似乎工作正常。但是,我认为我只是遗漏了一些小东西,如何将文件 ID 从 Picker.html 传递回我的 Google 脚本以继续我的流程?

如果有帮助,我现在正在使用 Google 文档中提供的基本回调。我假设这是将进行更改的地方。只是不知道该怎么做。

  function pickerCallback(data) {
    var action = data[google.picker.Response.ACTION];
    if (action == google.picker.Action.PICKED) {
      var doc = data[google.picker.Response.DOCUMENTS][0];
      var id = doc[google.picker.Document.ID];
      var url = doc[google.picker.Document.URL];
      var title = doc[google.picker.Document.NAME];
      document.getElementById('result').innerHTML =
          '<b>You chose:</b><br>Name: <a href="' + url + '">' + title + '</a><br>ID: ' + id;
    } else if (action == google.picker.Action.CANCEL) {
      document.getElementById('result').innerHTML = 'Picker canceled.';
    }
  }
4

2 回答 2

2

这应该可以工作:

在您的 pickerCallback(data) 函数中:

if (data.action == google.picker.Action.PICKED) {
  var fileId = data.docs[0].id;
  google.script.run
  .withSuccessHandler(useData) // this will call the google apps script function in your Code.gs file
  .doSomething(fileId); // this is a function in your JavaScript section where you will do something with the code you got from your apps script function  
}

function useData(data) {
 // do something with the data
}

在 Code.gs 中,创建一个函数来处理来自选取器的输入:

function doSomething(fileId) {
  // do an operation in Drive with the fileId
  var file = DriveApp.getFileById(fileId);
  var fileName = file.getName();
  return fileName;
}
于 2014-05-22T02:41:23.673 回答
0

First of all, open the chrome developer console when you are running this so you can see any errors that happen client side (when the picker is active). 您还可以使用 console.log 报告 Chrome 控制台中的任何变量值。

其次,对服务器的调用是异步工作的,因此这意味着在您的代码中,您将收到消息“脚本已运行”,而实际上它还没有。所发生的只是 google.script.run 要求您执行服务器端函数。

这就是为什么你有 withSuccessHandler 和 withFailureHandler 的原因。

所以你应该做

google.script.run

.withSuccessHandler (function (response) {
  document.getElementById('result').innerHTML = 'it worked'
})

.withFailureHandler (function (err) {
  document.getElementById('result').innerHTML = err;
})
.justatest (fileId);

并返回服务器脚本

function justatest(fileId) {
  Logger.log (fileId);
}

如果您随后返回并查看脚本日志文件,您应该会看到 fileId。

于 2016-03-26T11:35:54.817 回答