繁体   English   中英

将数据从 HTML 表单发送到 Google 表格

[英]Sending data from HTML form to Google Sheets

我目前正在尝试基于 David McCoy 的文章实现一个非常简单的电子邮件列表系统。 https://medium.com/@dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175

尽管我在 Stackoverflow 上遇到了一些类似的问题,但我仍然无法发现我的代码出了什么问题。

这是我的 HTML 表单:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Form to Google Sheets</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="./css/teste.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    </head>
    <body>
        <section class="container">

            <div class="fundo">

                <form id="reset" name="subscriptionform">

                    <label>Email
                    <input type="email_submit" 
                    id="email_submit" name="email" class="feedback-input" 
                    placeholder="Email" required>
                    </label><br>

                    <input type="submit" value="ENVIAR" id = "submit">
                </form>
            </div>

            <script>
            $('#subscriptionform').submit(function(e){
                    e.preventDefault();
                    formSubmit();
                })

                function formSubmit(){
                    var emailSubmitName = $('#email_submit').val();
                    if (emailSubmitName != ''){
                        var $form = $("#subscriptionform"),
                            url='https://(...)'
                        $.ajax({
                            url: url,
                            method: "GET",
                            dataType: "json",
                            data: $form.serializeObject(),
                            success: function(response){
                                $('#subscriptionform')[0].reset();
                                return true
                            } 
                        })
                    }
                    else{
                        return false
                    }
                }
            </script>

        </section>
    </body>
</html>

这是我复制并粘贴到我的 Google Sheet 上的 Web 应用程序代码: https : //gist.github.com/willpatera/ee41ae374d3c9839c2d6#file-google_script-gs

// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-

script-using-postget-methods-with-ajax-example/

function doGet(e){
  return handleResponse(e);
}

// Usage
//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "Sheet1";

//  2. Run > setup
//
//  3. Publish > Deploy as web app 
//    - enter Project Version name and click 'Save New Version' 
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously) 
//
//  4. Copy the 'Current web app URL' and post this in your form/script action 
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function


function doPost(e){
  return handleResponse(e);
}

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = []; 
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}

预先感谢您的关注!

为了获得表单对象,您需要使用#reset作为选择器 [1] 而不是#subscriptionform ,因为“reset”是表单元素的 id。 改变这个:

$('#subscriptionform') 

为了这:

$('#reset')

[1] https://www.w3schools.com/jquery/jquery_ref_selectors.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM