英文:
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.
<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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论