Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

forms - Prevent HTML Page Refresh

At this stage I'm mostly used to backend Javascript and server side Java, so my HTML is not as savvy as it needs to be.

I've built several applications that require user input with Apps script, but I was using the now deprecated UI service, as I'm not a designer and this provided an easy way to design simple pages to pass data back and forth. With the UI service having been deprecated for some time, I'm begging the arduous task of migrating these services to the HTML service, and I'm noticing some difference in behavior.

For example, when submitting a form, the entire page refreshes to a blank page, and I can't seem to prevent that. The UI service would remain static for information re-entry, and I can't find a working method to get the HTML service to either stop refreshing or reload the form.

Simple code to reproduce my issue:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('test')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function logValues(value){
  Logger.log('Something worked....');
}

With the index file being:

<form>
<input type="submit" value="Book Meeting" onclick="google.script.run
        .logValues()">
</form>

Some things I've tried:

1) Adding a callback to the 'doGet' function, to attempt to get the page to load again. 2) Adding a whole new function to try and call a NEW HTML page.

The issue here is my poor understanding of the HTML service, but is there a simple way for me to just clear the form for re-submission, or alternatively just reload the page? None of the other questions I've found on SO adequately answer this question in a way I can understand.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you're technically submitting your form by clicking the submit button, then that creates the page refresh. You need to cancel the submit event with the preventDefault function, which "Cancels the event if it is cancelable, without stopping further propagation of the event."

See the docs here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

So maybe you can try something along these lines (straight from the docs):

function stopDefAction(evt) {
    evt.preventDefault();
}

document.getElementById('my-checkbox').addEventListener('click', stopDefAction, false);

Another option is to remove the form/input elements and simply use a button element instead, which doesn't trigger a page refresh on click.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...