且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止HTML页面刷新

更新时间:2023-12-01 22:54:28

由于您在技术上通过点击提交按钮来提交表单,那么会创建页面刷新。您需要使用preventDefault函数取消提交事件,该函数如果可以取消该事件,则取消该事件,而不会停止进一步传播该事件。



请参阅文档: https://developer.mozilla.org/en-US/ docs / Web / API / Event / preventDefault



因此,也许你可以尝试以下几行(直接从文档中获得):

 函数stopDefAction(evt){
evt.preventDefault();
}

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

另一个选项是删除表单/输入元素,并简单地使用一个按钮元素, t在点击时触发页面刷新。


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.

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.