是否可以将 js 变量发送到谷歌表格?(不是表格数据)

2023-10-02前端开发问题
6

本文介绍了是否可以将 js 变量发送到谷歌表格?(不是表格数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

根据用户在我的网络应用程序上选择的内容,我创建了一些变量.我想将这些变量发送到谷歌表 - 这可能吗?我已经将数据从表单发送到谷歌表格.因为变量是在用户提交表单的同时创建的,所以我想将表单数据以及这些变量放入工作表中.

I have some variables that get created depending on what a user selects on my web app. I want to send those variables to a google sheet - is this possible? I already send data from a form to google sheets. Because the variables get created at the same time a user submits the form I want to put the form data as well as those variables into the sheet.

这是当前的js(为了简洁起见,左表html):

Here is the current js (left form html out to be concise):

$('#CompleteOrder').on('click', function(event){
                        event.preventDefault();

                        const scriptURL = 'https://script.google.com/macros/s/...................'
                        const form = document.forms['submit']

                        fetch(scriptURL, { method: 'POST', body: new FormData(form)})
                        .then(response => console.log('Success!', response))
                        .catch(error => console.error('Error!', error.message))

                  });

这里是我想用表单数据添加到谷歌表的变量的js:

And here is the js for the variables I want to add to the google sheet with the form data:

var ti = 1;
            $.each(products, function (i) {
                var productID = Number(products[i]['id']);
                var productImage = products[i]['image'];
                var productColor = products[i]['color'];
                var productSize = products[i]['size'];
                var productName = products[i]['name'];
                var productPrice = Number(products[i]['price']);
                var productQty = Number(products[i]['qty']);

                body = body + '<tr><td><span>' + productName + '</span></td><td><span>' + productColor + '</span></td><td><span>' + productSize + 'L</span></td><td><span data-prefix>$</span><span >' + productPrice + '</span></td><td><span>' + productQty + '</span></td><td><span data-prefix>$</span><span>' + (productPrice * productQty) + '</span></td></tr>';
                total = total + (productPrice * productQty);


            });

谢谢

我被卡住的地方是如何获取一个 js 变量并发送到谷歌表格.表格工作在那里没有问题.我找不到任何关于如何在不使用标签的情况下将变量发送到工作表的信息.我什至一直在搞乱将对象转换为表单数据.并且没有关于如何将表单数据以及 js 变量发送到同一张表的说明.

Where I am stuck is how to take a js variable and send to a google sheet. The form works there is no problem there. I can't find anything on how to send a variable to a sheet without using tags. I've even been messing with converting the object to form data. And no where is there an explanation on how to send form data as well as js variables to the same sheet.

Form

<form name="submit">
                            <div class="form-group">
                                <label for="cus-name">Name</label>
                                <input type="text" name="name" class="form-control form-control" id="cus-name"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-address">Street Address</label>
                                <input type="text" name="address" class="form-control form-control" id="cus-address"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-city">City</label>
                                <input type="text" name="city" class="form-control form-control" id="cus-city"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-state">Province</label>
                                <input type="text" name="province" class="form-control form-control" id="cus-state"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-zipcode">Zipcode</label>
                                <input type="text" name="zip" class="form-control form-control" id="cus-zipcode"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-phone">Phone Number</label>
                                <input type="text" name="number" class="form-control form-control" id="cus-phone"></input>
                            </div>
                            <div class="form-group">
                                <label for="cus-email">Email Address</label>
                                <input type="email" name="email" class="form-control form-control" id="cus-email"></input>
                            </div>




                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-success" id="CompleteOrder">Complete Order</button>
                    </div>

                                           </form>

谷歌脚本

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

推荐答案

看来你问题的核心是

如何创建 fetch() 的主体参数,使其包含表单数据对象和 JavaScript 变量中的其他值.

How to to create the fetch()'s body argument in such way that it includes both the form data object and other values from JavaScript variables.

new FormData(form) 返回一个 FormData 对象.

new FormData(form) returns a FormData object.

要将 HTML 表单中未包含的值添加到现有 FormData,请使用 FormData.append()

To add a value not included on the HTML form to an existing FormData use FormData.append()

将上述内容应用于代码以添加一个值的一种方法是替换

One way to apply the above to the code to add one value is to replace

fetch(scriptURL, { method: 'POST', body: new FormData(form)})
                        .then(response => console.log('Success!', response))
                        .catch(error => console.error('Error!', error.message))

通过类似的方式:

var something = 'New value';
var fetchBody = new FormData(form);
fetchBody.append('newKey',something);
fetch(scriptURL, { method: 'POST', body: fetchBody})
                        .then(response => console.log('Success!', response))
                        .catch(error => console.error('Error!', error.message))

要添加更多变量,请根据需要添加更多 fetchBody.append().

To add more variables, add more fetchBody.append() as needed.

注意:我还没有测试以上内容.

Note: I didn't tested the above yet.

相关问题

  • 将变量附加到FormData

参考文献

  • fetch() 简介

这篇关于是否可以将 js 变量发送到谷歌表格?(不是表格数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437