如何使用JavaScript将数据从HTML表单发送到Google电子表格?

我正在尝试构建一个Web应用程序,用于记录Google电子表格中表单中的数据。 要做到这一点,我必须使用JavaScript(JSON或AJAX请求也会起作用),但我不能使用Google Apps脚本,因为我需要用户继续使用我的页面而GAS不允许这样做。

我对JSON请求并不是很了解,但我试图追加一个:毫不奇怪,它不起作用也不奇怪,我不知道为什么。

我不确定我用来发出请求的URL和代码是否正确,但不知道如何继续,很难知道我的代码中有什么问题。

那是我的forms:

`

隐藏值设置为提供ID号和用户的路径。

check()函数将检查表单并(应该)发出请求并写入GSpreadSheet

  function check() { document.getElementById('errorForm').innerHTML = ""; var a = document.getElementById('area').value; var idN = document.getElementById('idN').value; var n = document.getElementById('nome').value; var c = document.getElementById('cognome').value; var m = document.getElementById('mat').value; var em= document.getElementById('mail').value; var t = document.getElementById('testo').value; // check the possible errors and set error messages. // if msg is not empty, writes the messages in my page. } else if(msg == "") { var xhr = new XMLHttpRequest(); var key = mySheetKey, sName = mySheetName, url = "https://sheets.googleapis.com/v4/spreadsheets/"+key+"/values/"+ sName + ":append?valueInputOption=USER_ENTERED"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function() { if(xhr.readyState === 4 && xhr.status === 200) { var json = JSON.parse(xhr.responseText); } // Here I should create the object made of my variables I read // from my form at the beginning of the code and send the request that // should append my datas to my Spreadsheet xhr.send(); } } 

正如我之前所说的,我的代码看起来类似于我在网上找到的几个代码,但它不起作用,我不知道如何理解错误。

您能否请给我一些提示或建议或一些可以帮助我将数据附加到Google电子表格的示例?

一个简单的电子表格包含Web应用程序示例

 $(function() { $('#btn1').click(validate); $('#txt4').val(''); $('#txt3').val(''); $('#txt2').val(''); $('#txt1').val('') }); function validate() { var txt1 = document.getElementById('txt1').value || ' '; var txt2 = document.getElementById('txt2').value || ' '; var txt3 = document.getElementById('txt3').value || ' '; var txt4 = document.getElementById('txt4').value || ' '; var a = [txt1,txt2,txt3,txt4]; if(txt1 && txt2 && txt3 && txt4) { google.script.run .withSuccessHandler(setResponse) .getData(a); return true; } else { alert('All fields must be completed.'); } } 

整个例子:

HTML:

       

Text 1
Text 2
Text 3
Text 4

Apps脚本:

 function getData(a) { var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'HH:mm:ss"); a.push(ts); SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Login').appendRow(a); return true; } function doGet() { var html = HtmlService.createHtmlOutputFromFile('index'); return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) } 

我的简单电子表格:

在此处输入图像描述

好消息是,您现在使用Google Chrome调试器可能比开始之前好多了。

Interesting Posts