如何在没有凭据的情况下将数据发布到联机表

时间:2013-05-31 13:50:10

标签: google-app-engine post google-apps-script google-sheets google-fusion-tables

我有一个生成数据的HTML页面(表格行)。我想在一个可以访问/下载的在线表中存储来自所有客户端的行(最好由所有者单独存储,因此匿名客户端只能添加行)

可能的解决方案和遇到的问题:

  • Google电子表格+谷歌应用脚​​本 - 如何进行跨源POST请求?
  • Google fusion tables - 如何从匿名客户端添加行?那可能吗?
  • 谷歌应用引擎 - 可能,但这个简单的任务似乎太耗时。

1 个答案:

答案 0 :(得分:0)

我找到了关于如何进行跨域POST的答案,所以我设法用应用程序脚本+电子表格做了我想做的事情:

应用脚本:

function doPost(request) {
    var ss = SpreadsheetApp.openById(id);
    var sheet = ss.getSheets()[0];
    if (request.parameters.row != null) {
      sheet.appendRow(Utilities.jsonParse(request.parameters.row));
    }
}

客户端javascript(来自https://stackoverflow.com/a/6169703/378594):

function crossDomainPost(paramsDict, url) {
    // Add the iframe with a unique name
    var iframe = document.createElement("iframe");
    var uniqueString = "SOME_UNIQUE_STRING";
    document.body.appendChild(iframe);
    iframe.style.display = "none";
    iframe.contentWindow.name = uniqueString;

    // construct a form with hidden inputs, targeting the iframe
    var form = document.createElement("form");
    form.target = uniqueString;
    form.action = url;
    form.method = "POST";

    // repeat for each parameter
    for (i in paramsDict) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = i;
        input.value = paramsDict[i];
        form.appendChild(input);   
    }

    document.body.appendChild(form);
    form.submit();
}

crossDomainPost({'row': JSON.stringify([123, 123, 1211])}, serverURL);

请注意,类似的方案应适用于Google融合表。