首页 > 解决方案 > 在 Javascript 中调用 GAS 的 doPost 函数

问题描述

我需要doPost从我的 Javascript 代码中调用 Google Apps 脚本端的一个函数。

我已经使用 a 完成了它,doGet但是我需要传递很多变量,所以 adoGet不是最好的。

这是我用于 的代码doGet,它适用于具有少量输入的表单,但我需要以更大的形式实现逻辑。

我必须从按钮调用函数

<input type="button" onclick="get()" value="Go" class="btn">

JS:

function get() {
    var SCRIPT_URL = "https://script.google.com/macros/s/key/exec";           
    $.getJSON(SCRIPT_URL + "?a="+ $("#a").val(),
    { method: "populate_list" },
    function (data) {
        alert(JSON.stringify(data));
    });
};

在 Google Apps 脚本中,这是我拥有的 doPost 函数

function doPost(e) {
    if (e.parameter.method=="populate_list") {
        SpreadsheetApp.getActiveSheet().getRange('F2').setValue(e.parameter.a);
    }
}

我需要的是按钮调用的函数 get() 但对于 doPost 的等价物,因此它调用我在 GAS 中的 doPost 函数

标签: javascriptjquerygoogle-apps-scripttriggers

解决方案


Jquery $.post() 适用于此,我从表单中获取值并将其传递给脚本 url。

JS:

var v_name = $("#name").val();
$.post("https://script.google.com/macros/s/KEY/exec",
        {
            index: selectedUser,
            name: v_name,
            variableName: variableValue
        },
        function (data) {
            console.log(data.name);
        }, 'json');

谷歌脚本

function doPost(e) {

    var sheet = SpreadsheetApp.getActiveSheet();

    sheet.getRange('B'+e.parameter.index + "").setValue(e.parameter.name);
}

推荐阅读