POST到外部URL (webhook),但重定向到不同的URL

POST to external URL (webhook) but redirect to different URL

本文关键字:URL 重定向 外部 webhook POST      更新时间:2023-09-26

在我的表单中,我将数据发布到一个外部url,这是一个webhook。在用户提交并将数据传递给webhook之后,我想将用户重定向到确认页面。

下面的代码有问题。当用户提交表单时,jQuery确实会将用户带到确认页面,但是表单数据不会触发webhook(数据不会被收集)。有人能告诉我哪里出错了吗?

下面是我的代码:

HTML

<form action="https://externalurl.com/webhook" method="POST">
     <input id="email" name="email">
     <input id="firstname" name="firstname">
     <input id="lastname" name="lastname">
     <button type="submit">Submit</button>
</form>
JQuery

    $('form').submit(function() {
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: 'json',
        success: function(json) {
           window.location.href = "https://www.mypage.com/confirmation";
          }
    });
    return false;
});

Thanks in advance

表单中有提交按钮吗?

您没有向webhook发送任何数据。试一试…

$('form').submit(function() {
$.ajax({
    type: 'POST',
    url: $(this).attr('action'),
    data: {
        "email": document.getElementById('email').value
        // get other fields
    },
    dataType: 'json',
    success: function(json) {
      }
});
return false;
});

或者如果你的实际表单更大,那么有很多方法可以将整个表单的数据序列化成json。

编辑:如果你想调试你的ajax调用,那么chrome的开发者工具的网络选项卡将让你看到你发送到服务器的确切内容,以及它的响应。

如果web与webhook不在同一个域中,则必须在webhook服务器中配置CORS策略,或者使用jsonp等替代策略。