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

时间:2018-09-18 22:38:45

标签: javascript html

我想通过两个不同的API发送表单数据。有什么可能的出路吗?

2 个答案:

答案 0 :(得分:1)

就像罗宾所说,编写一个事件处理程序,在提交时发送两个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>

答案 1 :(得分:0)

最好在第一个ajax完成后再使用第二个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>
相关问题