POST请求获取API阻止重定向 [英] POST request Fetch API prevent redirect

查看:72
本文介绍了POST请求获取API阻止重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想制作一个纯html和javascript表单并将其提交到服务器.

So i want to make a pure html and javascript form and submit it to server.

这是我的html表单代码:

Here is my html form code:

<form id="email-signup" action="http://www.server.com" method="post">
    <input id="firstname-input" type="hidden" name="firstname" value="">
    <input type="text" name="email" placeholder="Input Email">
    <input type="hidden" name="campaign[id]" value="1">
    <input type="hidden" name="campaign[name]" value="Text Campaign">
    <input type="submit" value="Submit">
</form>

这是我的JavaScript代码:

And here is my javascript code:

var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
  event.preventDefault()
  fetch("http://www.endpoint.api", {
    method: "POST",
    body: new FormData(document.getElementById('email-signup'))
  })
})
  .then(() => {
  alert('Selamat email anda sudah terdaftar!')
})

问题是,每当我向该表单提交电子邮件时,都会将我重定向到新页面,并成功回复.我想阻止这种情况的发生,而是会弹出一条警报,告诉我电子邮件提交成功.

The problem is, whenever i submit an email to that form it redirects me to a new page with a response of success. I want to prevent that to happen and instead it will pop up an alert that tells me the email submission is succeeded.

推荐答案

可能是将JavaScript代码放在HTML之前,并将.then()放在EventListner之后.

Possibly, you are putting JavaScript code before HTML and .then() after EventListner.

解决方案是将JavaScript代码放在HTML后面,然后将.then()放在获取之后.

The solution will be to place JavaScript code after HTML and place .then() just after fetch.

    <form id="email-signup" action="http://www.server.com" method="post">
        <input id="firstname-input" type="hidden" name="firstname" value="">
        <input type="text" name="email" placeholder="Input Email">
        <input type="hidden" name="campaign[id]" value="1">
        <input type="hidden" name="campaign[name]" value="Text Campaign">
        <input type="submit" value="Submit">
    </form>

<script>
    var element = document.getElementById("email-signup");
    element.addEventListener("submit", function(event) {
        event.preventDefault()
        fetch("", {
            method: "POST",
            body: new FormData(document.getElementById('email-signup'))
            }).then(() => {
            alert('Selamat email anda sudah terdaftar!')
        })
    })
</script>

这篇关于POST请求获取API阻止重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆