[英]Retrieve and update values in Google spreadsheet by row ID by using HTML form
我能够使用这些列创建一个谷歌电子表格(在这里找到想法):产品 | 尺寸 | uid其中 uid 是随机生成的五个数字 ID (=RANDBETWEEN(10000;99999))。 然后我使用了以下应用程序脚本:
// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
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());
}
然后,我把这个 php 文件放在一起:
<?php
if (isset($_GET['product'])) $product = $_GET['product'];
if (isset($_GET['size'])) $size = $_GET['size'];
if (isset($_GET['uid'])) $uid = $_GET['uid'];
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Submit rows</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
Submit new row to google sheet.
<form id="test-form">
<div>
<label>product</label>
<input type="text" name="product" value="<?php echo $product; ?>"/>
</div>
<div>
<label>size</label>
<input type="text" name="size" value="<?php echo $size; ?>"/>
</div>
<div>
<label>UID</label>
<input type="text" name="uid" value="<?php echo $uid; ?>"/>
</div>
<div>
<button type="submit" id="submit-form">Submit form</button>
</div>
<div class="thanks"></div>
</form>
<script>
$(document).ready(function(){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var form = $('form#test-form'),
url = 'https://script.google.com/macros/s/KEY/exec';
form.submit(function(e){
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: form.serializeObject()
});
$(".thanks").html("Sent to sheet.").css("font-size","2rem");
$(".form-control").remove();
$("#submit").remove();
});
});
</script>
</body>
</html>
为什么会这样? 我有一个二维码,当它被扫描时,用户会被定向到 url,如下所示:htttps://samplesite.com/index.php?product=Pants&size=large&uid=12345
因此,表单字段由 qr 代码/链接中的值预先填充。 提交表单,将值写入谷歌电子表格,一切都很好。
但现在到问题部分:,) 产品上有另一个二维码,扫描时:它会像这样打开 url:htttps.//samplesite.com/edit?php?uid=12345
我希望打开另一个页面,其中列出了同一 google 电子表格的行值,其中 uid 为 12345。使用 php,它可能类似于select * from sheet_id where uid='12345'然后定义列值,但显然这并不容易。
我做了一些搜索并建议使用 tabletop.js,但他们( https://github.com/jsoma/tabletop )不再推荐它。
谢谢你。
一种方法是直接在doGet()
中实现 HTML 表单,并使用google.script.run.withSuccessHandler(yourClientFunction).yourServerFunction(someParam)在 HTML 表单和电子表格之间推送和拉取数据。 这将自动处理身份验证。 请参阅Web 应用演示。
或者,在您的客户端代码中使用表格 API 。 您不需要doGet()
但需要处理身份验证。
您不应该使用randbetween()
创建 ID,因为最终会发生冲突。 如果您只为 ID 分配五位数字并且从不检查重复项,那么生日问题实际上会保证在前几百个 ID 之后会发生冲突。 您应该使用递增计数器。 如果这不可能,请使用Utilities.getUuid()
或类似方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.