我有一个谷歌表格脚本,允许用户输入某些数据。我希望能够在用户单击“确定”时将这些值传递回 Google 应用脚本中的函数。
这是我正在尝试使用的 Google 表格脚本。函数 checkLogin 确实会被调用,直到我尝试从网页将值传递给它为止。
g脚本
function onOpen() {
openLogin();
SpreadsheetApp.getUi()
.createMenu('Dialog')
.addItem('Open', 'openLogin')
.addToUi()
}
function openLogin() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Login Form');
}
function checkLogin(user_name, user_password, staff, student) {
SpreadsheetApp.getUi().alert(user_name);
}
网页代码如下:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
First name:
<input type="text" name="user_name"><br><br>
Last name:
<input type="password" name="user_password"><br><br>
Staff or Student?
<br>
<input type="radio" name="staff" value="staff" checked> Staff<br>
<input type="radio" name="student" value="student"> Student<br>
<br><br>
<input type="button" value="OK"
onclick="google.script.run.checkLogin(user_name, user_password, staff, student)" />
<input type="button" value="Close"
onclick="google.script.host.close()" />
</form>
</body>
</html>
我希望有人能指出我正确的方向。谢谢
最佳答案
提交登录信息的按钮需要更改。需要有一种方法来收集输入信息。目前,表单中的任何信息都没有发送到服务器。要么需要将表单对象发送到服务器,要么需要以其他方式检索值。如果你想使用表单对象,你必须通过 this.parentNode
来获取它
onclick="google.script.run.withSuccessHandler(showMsgForLoginAttempt)
.checkLogin(this.parentNode)" />
添加<script>
标记为index.html
带有成功处理程序的文件。添加withSuccessHandler()
到google.script.run
服务器调用。
索引 html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
First name:
<input type="text" name="user_name"><br><br>
Password:
<input type="password" name="user_password"><br><br>
Staff or Student?
<br>
<input type="radio" name="staff" value="staff" checked> Staff<br>
<input type="radio" name="student" value="student"> Student<br>
<br><br>
<input type="button" value="OK"
onclick="google.script.run.withSuccessHandler(showMsgForLoginAttempt).checkLogin(this.parentNode)" />
<input type="button" value="Close"
onclick="google.script.host.close()" />
</form>
</body>
<script>
window.showMsgForLoginAttempt = function(valueFromServer) {
console.log('showMsgForLoginAttempt ran');
alert('Your attempt: ' + valueFromServer);
};
</script>
</html>
服务器代码:
function checkLogin(formObject) {
var passwordsMatch;
Logger.log('formObject: ' + formObject)
Logger.log('formObject: ' + formObject.user_name);
formObject
//SpreadsheetApp.getUi().alert('Hello, world!');
passwordsMatch = true; //check password
if (passwordsMatch) {
return true;
} else {
return false;
}
}
关于javascript - 将网络表单值返回至 Google 应用脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385328/