【问题标题】:send data in object from html by fetch to spreadsheet通过 fetch 将对象中的数据从 html 发送到电子表格
【发布时间】:2021-08-12 18:33:42
【问题描述】:

我尝试将数据从 html 输入发送到电子表格,如视频中的作者 https://www.youtube.com/watch?v=yiPnkBEHqf0&list=PLRmEk9smitaVGAAhgU0Pdc2sEs7yxDrEk

在 JS 和 HTML 中我这样写:

const url = "https://script.google.com/macros/s/AKfycbzZe824lIxa-hNsO71xoFfq5qXbFaDKhHZeACrQgLMCjU_EjvY/exec";

var loginText = document.getElementById("tLogin");
var tableText = document.getElementById("tTable");
var orderText = document.getElementById("tOrder");

function testGS(){
    var userInfo = {
            login: loginText.value,
            table: tableText.value,
            order: orderText.value,
            sdate: new Date().toLocaleDateString(),
    };
    fetch(url, {
        method: 'POST',
        headers: {"Content-Type": 'application/json'},
        body: JSON.stringify(userInfo)
        })
        .then((res) => res.text())
        .then((text) => console.log(text));
}           

document.getElementById("del").addEventListener("click", testGS);
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" href="CSS/main_page_style.css">
    <link rel="icon" href="Image/favicon.png" type="png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
       integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
    <div class="conteiner">
        <form novalidate>
                <h6 class="title">PACKING</h6>
                <img src="Image/mainImg.jpg" class="img-fluid" alt="...">
            <div class="dws-input">
                <div class="col-md-3"></div>
                <div>
                    <div>
                        <button id="del" type="button">&lt;======СБРОС</button>
                    </div>
                    <div class="form-floating mb-3 mt-3">
                        <input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Login:" autofocus > 
                        <label for="tLogin">Логин:</label>
                    </div>
                    <div class="form-floating mb-3 mt-3">
                        <input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Table:" >
                        <label for="tTable">Номер стола:</label>
                    </div>
                </div>
                <div class="form-floating mb-3 mt-3">
                    <input type="text"  novalidate class="form-control" id="tOrder" name= "text" placeholder= "Order:" >
                    <label for="type3">Заказ:</label>
                </div> 
            </div>  
        </form>
    </div>
    <script src="JS/fetchNew.js"></script>

</body>

</html>

在 GAS 中我这样写:

function doGet() {

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("LOG_history");  
  const data = ws.getRange("A1").getDataRegion().getValues();
  const headers = data.shift();

  const jsonArray = data.map(r => {
    let obj = {};
     headers.forEach((h , i) => {
       obj[h] = r[i];
     });
    return obj;
  })
  const response = [{status: 200, data: jsonArray}];
  return sendJSON_(response);
}

function doPost(e){

  let jsonResponse;

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("LOG_history");
  const headers = ws.getRange(1,1,1,ws.getLastColumn()).getValues()[0];
  const headersOriginalOrder = headers.slice();
  headersOriginalOrder.shift();
  //remove id columns header
  headers.shift();
  headers.sort();

  const body = e.postData.contents;
  const bodyJSON = JSON.parse(body);
  const headersPassed = Object.keys(bodyJSON).sort();

  if(!compareTwoArray_(headers, headersPassed)){
      jsonResponse = [{status:500, message:"Invalid Arguments Passed"}];
      return sendJSON_(jsonResponse);
  }

  const arrayOfData = headersOriginalOrder.map(h => bodyJSON[h]);
  
  const aoaIds = ws.getRange(2,1,ws.getLastRow()-1,1).getValues();
  const newIDNumber = getMaxFromArrayOfArray_(aoaIds) + 1;
  arrayOfData.unshift(newIDNumber);
  ws.appendRow(arrayOfData);
  
  return ContentService.createTextOutput("ok");
}

//return true if all ites are the same
function compareTwoArray_(arr1, arr2){
  if (arr1.length !== arr2.length) return false;

    for (let i = 0; i < arr1.length; i ++){
      if (arr1[i] !== arr2[i]) return false;
    }
  return true;
}

function sendJSON_(jsonResponse){
  return ContentService
      .createTextOutput(JSON.stringify(jsonResponse))
      .setMimeType(ContentService.MimeType.JSON);
      
}

//return the highest number / id
function getMaxFromArrayOfArray_(aoa){
  let maxID = 0;
  aoa.forEach(r => {
    if (r[0] > maxID) maxID = r[0];
  });
  return maxID;
}

我需要将输入 html 页面中的数据发送到 js-function 中的对象 UserInfo 中,并将它们附加到电子表格中,但没有任何反应。

如果我像这样“body: JSON.stringify(userInfo)”将 userInfo 对象放入 fetch 中,我会犯错。 我该如何组织呢?谢谢!

我有一个通知:如果我在 fetch "mode: 'no-cors'" 中写入数据,则数据会附加到电子表格中,但不会显示来自 doPost 的返回信息。我需要返回信息....((

【问题讨论】:

    标签: html google-apps-script


    【解决方案1】:

    您是否必须对对象进行字符串化才能在服务器和客户端之间传递?我的 html 中有这段代码,用于从服务器取回数据。

    function succeed (res)   {
            alert('Begin succeed' );
            console.log('Begin succeed' );
            if (res == null)    {
              alert('Error: response was null!' );
              console.log('Error: response was null!' );
              return;
            }
            
            try  {
              alert(JSON.stringify(res) );
              console.log(JSON.stringify(res) );
              alert(res);
              console.log(res);
            }    catch (err)   {
              alert('catch error trying to display res' );
              console.log('catch error trying to display res' );
            }
            
            try  {
              document.getElementById('listDisplay').innerHTML = JSON.stringify(res);
            }    catch (err)   {
              alert('catch error trying to put res into textarea' );
              console.log('catch error trying to put res into textarea' );
            }
          }
          
          function fail (err) {
            alert('Begin fail' );
            console.log('Begin fail' );
            alert('Error occurred', err);
            console.log('Error occurred', err);
            
            document.getElementById('listDisplay').innerHTML = 'ERROR: ' + err;
          }
    

    【讨论】:

    • 谢谢。我认为您的脚本会派上用场,当我将显示操作的结果时。但我现在需要在电子表格行中附加数据))
    猜你喜欢
    • 2013-01-20
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2014-02-01
    相关资源
    最近更新 更多