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

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

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

问题

  1. <form action="/search" method="post" id="search-form">
  2. <input type="search" name="search">
  3. <input type="submit" value="搜索">
  4. </form>
  5. <script>
  6. $("#search-form").submit(function(event) {
  7. event.preventDefault();
  8. })
  9. </script>

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

英文:
  1. <form action="/search" method="post" id="search-form">
  2. <input type="search" name="search">
  3. <input type="submit" value="Search">
  4. </form>
  5. <script>
  6. $("#search-form").submit(function(event) {
  7. event.preventDefault();
  8. })
  9. </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函数发送它。

  1. <form action="/search" method="post" id="search-form">
  2. <input type="search" name="search">
  3. <input type="submit" value="Search">
  4. </form>
  5. <script>
  6. $("#search-form").submit(function(event) {
  7. event.preventDefault();
  8. let formData = new FormData();
  9. $.each($(this).serializeArray(), function (key, input) {
  10. formData.append(input.name, input.value);
  11. });
  12. axios.post("/url", formData).then(() => /* do something*/);
  13. })
  14. </script>

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

英文:

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

  1. &lt;form action=&quot;/search&quot; method=&quot;post&quot; id=&quot;search-form&quot;&gt;
  2. &lt;input type=&quot;search&quot; name=&quot;search&quot;&gt;
  3. &lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;
  4. &lt;/form&gt;
  5. &lt;script&gt;
  6. $(&quot;#search-form&quot;).submit(function(event) {
  7. event.preventDefault();
  8. let formData = new FormData();
  9. $.each($(this).serializeArray(), function (key, input) {
  10. formData.append(input.name, input.value);
  11. });
  12. axios.post(&quot;/url&quot;, formData).then(() =&gt; /* do something*/);
  13. })
  14. &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:

确定