HTML form is not running a (withSuccessHandler)fun

2019-07-19 05:07发布

I have this HTML form in Google App Script(Sheets) that asks a user for a date value and then to submit the value. The HTML form runs. the only problem is the obj doesn't log. I can't figure out why this is.

The HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
   <form id="myForm">

    <input type="date" name="startDate" value="" id="demo" >
    <input type="button" style="font-family: verdana;" value="Submit" onclick="getStartDate()">

   </form> 
    <script>
  function success(msg) {
    alert(msg);
  }

  function getStartDate(){
    var form = document.getElementById("myForm").elements;
    var obj ={};
    for(var i = 0 ; i < form.length ; i++){
        var item = form.item(i);
        obj[item.name] = item.value;
    }
    google.script.run
    .withSuccessHandler(success)
    .getStartDate(obj);

    google.script.host.close();
  };
  </script>
  </body>
</html>

The Javascript:

function getStartDate(obj){
  Logger.log(obj)
}

This should output the object but it doesn't.

Thanks for your help!

1条回答
干净又极端
2楼-- · 2019-07-19 05:31

How about this modification?

Modification points:

  • google.script.run works by the asynchronous processing. So in your script, getStartDate() and success() are not run due to google.script.host.close().
  • getStartDate() at GAS side doesn't return values. So alert(msg) shows undefined.

When above points are reflected to your script, it becomes as follows.

Modified script:

HTML:

Please modify Javascript as follows.

function success(msg) {
  alert(JSON.stringify(msg)); // Modified
}

function getStartDate(){
  var form = document.getElementById("myForm").elements;
  var obj ={};
  for(var i = 0 ; i < form.length ; i++){
    var item = form.item(i);
    obj[item.name] = item.value;
  }
  google.script.run
  .withSuccessHandler(function(e) { // Modified
    success(e);
    google.script.host.close();
  })
  .getStartDate(obj);
};
GAS:
function getStartDate(obj){
  Logger.log(obj)
  return obj; // Modified
}

Note:

  • If you want to give the key to Submit, please add name to <input type="button" style="font-family: verdana;" value="Submit" onclick="getStartDate()">.
  • Of course, you can also move google.script.host.close() to success().

Reference:

If this was not what you want, please tell me. I would like to modify it.

查看更多
登录 后发表回答