Google Web App登录后无法渲染Google Sheets数据表格问题求助
问题根因
代码存在两个核心问题导致Table页面无法渲染跳转:
google.script.run是前端异步调用后端函数的客户端API,不会自动渲染后端返回的HtmlOutput对象。你当前代码调用LoadTable时没有绑定成功回调,后端渲染完成的Table页面内容被直接丢弃,没有代码负责把内容加载到当前页面。- 你定义的路由逻辑是绑定在
doGet触发的页面访问流程上的,直接通过google.script.run调用LoadTable属于普通后端函数执行,不会触发浏览器页面切换动作。
修复方案
方案1:回调替换页面内容(无需改动后端逻辑,推荐)
修改Login页面内嵌的JS代码,给LoadTable调用绑定成功回调,接收后端返回的页面内容后直接替换当前页面即可:
<script> function LoginUser() { var usercodeIn = document.getElementById("Usercode").value; var passwordIn = document.getElementById("Password").value; google.script.run.withSuccessHandler(function(User){ if(User != 'FALSE') // 账号密码校验通过 { document.getElementById("errorMessage").innerHTML = "welcome " + User ; // 绑定成功回调接收Table页面内容 google.script.run.withSuccessHandler(function(tableOutput){ // 提取HtmlOutput里的原始HTML内容,替换当前页面 document.open(); document.write(tableOutput.getContent()); document.close(); }).LoadTable(usercodeIn) ; } else // 校验不通过 { document.getElementById("errorMessage").innerHTML = "Wrong Password!"; } }).checkLogin(usercodeIn,passwordIn); } </script>
注意:必须调用getContent()方法拿到HtmlOutput对象的原始HTML字符串,才能直接写入页面。
方案2:复用已有路由逻辑做页面跳转
如果要使用你写的doGet路由逻辑,需要调整后端代码兼容路由传参,再让前端直接跳转对应路由地址:
- 修改后端
doGet函数,把请求参数传递给路由对应函数:
function doGet(e) { Route.path("Login",LoadLogin) ; Route.path("Table",LoadTable) ; if(Route[e.parameters.v]){ // 将GET请求参数传给路由处理函数 return Route[e.parameters.v](e.parameter) ; }else { return render("Login") ; } }
- 修改后端
LoadTable函数,从传入的参数对象中读取用户编码:
function LoadTable(params){ var Usercode = params.usercode; var TargetRow = GetRow(Usercode) ; var Data = PayrollSheet.getRange(TargetRow,1,1,18).getValues().flat(); var Round = PayrollSheet.getRange(1,2,1,2).getValues().flat(); return render("Table",{array:Data,round:Round}) ; }
- 修改前端登录成功后的逻辑,直接跳转到Table路由地址:
if(User != 'FALSE') { document.getElementById("errorMessage").innerHTML = "welcome " + User ; // 跳转至Table路由,携带编码参数 window.location.href = `?v=Table&usercode=${encodeURIComponent(usercodeIn)}`; }
内容的提问来源于stack exchange,提问作者Samatcha
相关产品推荐
相关产品推荐

