简体   繁体   English

如何在 go 模板中提交表单而不重新加载整个 html?

[英]How to submit form in go template without reloading the whole html?

<form action="/search" method="post" id="search-form">
    <input type="search" name="search">
    <input type="submit" value="Search">
</form>

<script>
    $("#search-form").submit(function(event) {
      event.preventDefault();
    })
</script>

When I am submitting the form and getting the values in with PostFormValue.当我提交表单并使用 PostFormValue 获取值时。 When clicking on submit button it reloads the whole page.单击提交按钮时,它会重新加载整个页面。 I just want to avoid that!!!我只是想避免这种情况!!!

You can use formData object then send it via axios or fetch functions.您可以使用 formData object 然后通过 axios 发送它或获取函数。

<form action="/search" method="post" id="search-form">
    <input type="search" name="search">
    <input type="submit" value="Search">
</form>
    
<script>
    $("#search-form").submit(function(event) {
        event.preventDefault();
        let formData = new FormData();
    
        $.each($(this).serializeArray(), function (key, input) {
            formData.append(input.name, input.value);
        });
        axios.post("/url", formData).then(() => /* do something*/);
    })
    
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM