为什么带有空值的对象密钥对不再从服务器传递到客户端?

Rad*_*dek 1 client-server web-applications google-apps-script

我有一个 Google 应用程序脚本 Web 应用程序,我在其中使用google.script.run.withSuccessHandler. 服务器端函数返回一个所有值为空的对象。MaterializeCSS自动完成需要 null

我的客户今天报告说 GAS 网络停止工作。之前是 10000000% 工作。我发现原因是 anull作为一个值。

工作示例应用程序在这里

https://script.google.com/macros/s/AKfycbzbg4YLndZ0zORBzgDc3ETLUdJeToUS1nKjORUa5fNxQt9syXmLlX1gDHzgS4w8iCBM9A/exec

https://script.google.com/d/1Uba73PIetb9fmrO44nwsmAd_epZTHy4lwz5bG3bURK3jqpd161JT0pf5/edit?usp=sharing

HTML代码

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Test
<script type="text/javascript">
 console.log("test")

document.addEventListener("DOMContentLoaded", function(event) { 
    google.script.run.withSuccessHandler(afterDataReceived)
                    .returnObject()
    });

function afterDataReceived(receivedData){
  console.log(receivedData)
}
     </script>
     </body>
</html>
Run Code Online (Sandbox Code Playgroud)

GS代码

function doGet(e) {

  var htmlTemplate = HtmlService.createTemplateFromFile("index").evaluate()

  return htmlTemplate
}

function returnObject(){

  var object = {}

  object.a = "123"
  object.b = null
  object.c = 123

console.log(object)  
  return object
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有人遇到同样的错误吗?如何解决这个问题?

The*_*ter 5

问题:

如果null是对象中 a 的值key,则当对象从服务器传递到客户端时,键值对会丢失,尽管null是合法参数。我可以确认该问题。

解决方案:

此处报告了该问题。如果其他人也遇到同样的问题,请为该问题添加星号。

作为非法参数的典型解决方法,JSON.stringify()在服务器端使用,将 传递string给客户端,并JSON.parse()在客户端获取对象内的空值。

服务器:

function returnObject(){
  return JSON.stringify({a:1,b:null,c:3});
}
Run Code Online (Sandbox Code Playgroud)

客户:

document.addEventListener("DOMContentLoaded",    
 function(event) { 
  google.script.run
    .withSuccessHandler(afterDataReceived)
    .returnObject()
});

function afterDataReceived(receivedData){
  console.log(JSON.parse(receivedData));
}
Run Code Online (Sandbox Code Playgroud)