在短时间内提交三种形式

Submit three forms within short timeout

我有三种形式,并不总是所有三种都被定义(在许多情况下它只是两种),但在任何情况下我都想发送它们。操作页面将执行某些操作。 当前脚本适用于 1 或 2 个表单,但不适用于 3 个表单。

有没有可能只用简单的 JS 或 CF 就可以完成?或者可能有更好的方法来处理这个问题?

<form id="CreateTask1" action=action.cfm>
<form id="CreateTask2" action=action.cfm>
<form id="CreateTask3" action=action.cfm>

   <script type="text/javascript">
      function submitforms() {
        if (document.getElementById('CreateTask1') != null)
            document.forms.CreateTask1.submit();
            window.setTimeout(function() {
        if (document.getElementById('CreateTask2') != null)
            document.forms.CreateTask2.submit();
            }, 100);
            window.setTimeout(function() {
        if (document.getElementById('CreateTask3') != null)
            document.forms.CreateTask3.submit();
            }, 100);
        }
    </script>

也许你应该使用 AJAX 来实现这一点。

因此,如果您要发送三种不同的表单,则可以通过多种方式进行异步请求。我们可以以现代方式使用一些像 JQuery 甚至纯 javascript 的库及其新功能(API Fetch),或者使用通常的 XMLHttpRequest。

Here 是关于在 for 循环中制作多个 XMLHttpRequests 的解释,在您的情况下,可以与 document.forms 长度匹配。

像这样:

 function sendForms() {
  var xhr = [],
    i;

  for (i = 0; i < document.forms.length; i++) {
    //for loop
    (function (i) {
      var form = document.forms[i];
      var input = document.getElementById("input1");
      var inputData = encodeURIComponent(input.value);
      xhr[i] = new XMLHttpRequest();
      url = "your_page.php?" + input.name + "=" + inputData;
      xhr[i].open("POST", url, true);
      xhr[i].onreadystatechange = function () {
        if (xhr[i].readyState === 4 && xhr[i].status === 200) {
          console.log(
            "Response from form " + i + " is [ " + xhr[i].responseText + "]"
          );
        }
      };
      xhr[i].send();
    })(i);
  }

}

sendForms();

您可能想要构建动态发送的参数,为此您可以使用 FormData 来帮助,或者考虑使用 JQuery 来简化步骤。

很抱歉之前没有提供更详细的答案,但我不知道你是否能够在你的项目中使用AJAX,但对我来说,使用这些超时看起来不太好解决方案。

我想你可以

 <form id="CreateTask1" action="action.cfm" target="iframe1"></form>
 <iframe name="iframe1" src="blank.html"></iframe>

 <form id="CreateTask2" action="action.cfm" target="iframe2"></form>
 <iframe name="iframe2" src="blank.html"></iframe>

 <form id="CreateTask3" action="action.cfm" target="iframe3"></form>
 <iframe name="iframe3" src="blank.html"></iframe>

<script type="text/javascript">
  function submitforms() {
    if (document.getElementById('CreateTask1') != null)
        document.forms.CreateTask1.submit();
        window.setTimeout(function() {
    if (document.getElementById('CreateTask2') != null)
        document.forms.CreateTask2.submit();
        }, 100);
        window.setTimeout(function() {
    if (document.getElementById('CreateTask3') != null)
        document.forms.CreateTask3.submit();
        }, 100);
    }
</script>