Google表格作为Ajax数据库

问题描述 投票:1回答:2

我正试图遵循这个指南:Google Sheets as a Database – INSERT with Apps Script using POST/GET methods (with ajax example)

我知道我要在电子表格中加入“Google Sheet / Apps Script Code”。但我不知道我要为Google Apps脚本添加'code.gs'和'index.html'。

因为stackoverflow示例带有'form.php'。

HTML

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

JavaScript的

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});

form.php的

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = $_POST['bar'];

由Hawksey改变

// fire off the request to /form.php
        request = $.ajax({
            url: "https://script.google.com/macros/s/AKfycbzV--xTooSkBLufMs4AnrCTdwZxVNtycTE4JNtaCze2UijXAg8/exec",
            type: "post",
            data: serializedData
        });

脚本的结尾是制作表单并使用ajax通过post发送数据到Google电子表格。

非常感谢你。

javascript php ajax google-apps-script google-sheets
2个回答
0
投票

试试这个....

code.公司

var logSheetId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Spreadsheet key

function doGet(e) 
{
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function uploadData(formObject) 
{
  try 
  {
    var userEmail = formObject.name;
    var userMessa = formObject.message;
    var ss = SpreadsheetApp.openById(logSheetId);
    var sheet = ss.getSheets()[0];
    sheet.appendRow([userEmail,userMessa]);
  } 
  catch (error) 
  {
    return error.toString();
  }
}  

form.html

<div>
<form id="myForm">
  Name: <input type="text" name="name" placeholder="Your name..."/>
  Message: <textarea type="text" name="message" placeholder="message..."></textarea>
  <input type="button" value="Submit"
      onclick="google.script.run
          .withSuccessHandler(updateUrl)
          .withFailureHandler(onFailure)
          .uploadData(this.parentNode)" />
</form>

<div id="output"></div>

<script>
    function updateUrl() {
        var div = document.getElementById('output');
        div.innerHTML = '<a>Data sent!</a>';
    }
    function onFailure(error) {
        alert(error.message);
    }
</script>

<style>
  input { display:block; margin: 20px; }
</style>
</div>

0
投票

这是一个有效但已弃用的解决方案。它有效,但我想用更新的功能来实现它。

var submissioSSKey = 'You Spreadsheet Key';//Change this key to your spreadsheet key
function doGet(){
  var app = UiApp.createApplication().setTitle('myApp');
  var panel = app.createVerticalPanel();
  var grid = app.createGrid(4, 2).setId('myGrid');
  var nameLabel = app.createLabel('Name');
  var nameTextBox = app.createTextBox().setWidth('150px').setName('name');
  var messageLabel = app.createLabel('Message');
  var messageTextArea = app.createTextArea().setWidth('150px').setName('message');
  var submitButton = app.createButton('Submit');
  var infoLabel = app.createLabel('Data inserted in sheet successfully..')
      .setVisible(false).setId('info');
  grid.setWidget(0, 0, nameLabel)
    .setWidget(0, 1, nameTextBox)
    .setWidget(1, 0, messageLabel)
    .setWidget(1, 1, messageTextArea)
    .setWidget(2, 1, submitButton)
    .setWidget(3, 1, infoLabel); 
  var handler = app.createServerClickHandler('insertInSS');
  handler.addCallbackElement(panel);
  submitButton.addClickHandler(handler);  
  panel.add(grid);
  app.add(panel);
  return app;
}

//Function to insert data in the sheet on clicking the submit button
function insertInSS(e){
  var app = UiApp.getActiveApplication();
  var name = e.parameter.name;
  var message = e.parameter.message;
  app.getElementById('info').setVisible(true).setStyleAttribute('color','red');

  var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
  var lastRow = sheet.getLastRow();
  var targetRange = sheet.getRange(lastRow+1, 1, 1, 2).setValues([[name,message]]);
  return app;
}

资料来源:Insert data in sheet using UI forms

© www.soinside.com 2019 - 2024. All rights reserved.