我们可以使用单个表单标签的动作发送两个帖子请求吗?

问题描述 投票:1回答:2

我想在两个不同的API上发送表单的数据。有没有可能的出路?

javascript html
2个回答
1
投票

就像Robin说的那样,编写一个事件处理程序,在提交时发送两个api请求。

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'firstAPIUrl',
            data: $('form').serialize(),
            success: function () {
              alert('first api was submitted');
            }
          });

           $.ajax({
            type: 'post',
            url: 'secondAPIurl',
            data: $('form').serialize(),
            success: function () {
              alert('second api submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="value">
      <input name="date" value="value">
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

0
投票

如果你在第一个完成之后使用第二个ajax,它会更好:

<script>
  $(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'firstAPIUrl',
        data: $('form').serialize(),
        success: function () {
          alert('first api was submitted');

          $.ajax({
            type: 'post',
            url: 'secondAPIurl',
            data: $('form').serialize(),
            success: function () {
              alert('second api submitted');
            }
          });
        }
      });

    });

  });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.