如何在不重新加载整个 HTML 的情况下提交 Go 模板中的表单?

huangapple go评论95阅读模式
英文:

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="搜索">
</form>

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

当我提交表单并使用PostFormValue获取值时,点击提交按钮会重新加载整个页面。我只想避免这种情况!

英文:
<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. When clicking on submit button it reloads the whole page. I just want to avoid that!!!

答案1

得分: 2

你可以使用formData对象,然后通过axios或fetch函数发送它。

<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>

请注意,这是一个HTML代码示例,用于在表单提交时使用axios发送formData对象。

英文:

You can use formData object then send it via axios or fetch functions.

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

huangapple
  • 本文由 发表于 2022年8月6日 04:34:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/73255028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定