提交表单到2个不同的网站第二通过javascript

submitting form to 2 different websites second via javascript

本文关键字:二通 javascript 网站 表单 2个 提交      更新时间:2023-09-26

我有一个情况,我想在同一时间发布表单数据到2个不同的位置。我没有控制的位置,他们是跨域。我在这里找到了一个以前的帖子,使用了一个iframe,我现在找不到,我已经合并了。它每次都提交给第一个,但第二个只提交了25%的时间。我需要它在所有主要浏览器中更可靠地工作。尝试使用ajax,但不能让它在IE跨域工作尝试在这个论坛提出的许多解决方案。谢谢。Ed

<form name="myForm" method="post" action="http://www.firstwebsite.com" onsubmit="return submit2nd()"  >
<input type="email" name="email" value='' />
<input type="submit" name="submit" />
</form>
<script>
function submit2nd(){
var x=document.forms["myForm"]["email"].value;
var iframe = document.createElement("iframe");
var uniqueString = "asderwegthyuq123";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
var form = document.createElement("form");
form.target = uniqueString;
form.action = "http://www.secondwebsite.com";
form.method = "POST";
var input = document.createElement("input");
input.type = "hidden";
input.name = "email";
input.value = x;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
return true;
}
</script>    

在提交时复制表单,并将表单提交到具有不同目标的两个iframe,或者使用AJAX。我强烈推荐使用JQuery这样的框架,这样你就不用担心兼容性问题了。

你的代码发生的事情是,它会在提交第一页时尝试提交到第二页。如果提交到第一页的内容在提交到第二页之前完成,则第二次提交将不会成功。如果您离开页面,当前页面中的所有脚本都将停止(因为您将转到www.firstwebsite.com)。

你可以这样做:

  1. 更改submit2nd(),使其提交第一和第二个网站。
  2. submit2nd()应该返回false,这样它就不会尝试提交到action属性中的页面。在提交后(点击提交按钮),复制表单。
  3. 第一个表单->将action更改为www.firstwebsite.com ->提交。
  4. 第二表单->将action更改为www.secondwebsite.com -> submit.

注意:如果您希望为此使用AJAX,只需确保您不会有跨域问题。在您的示例中,您尝试将表单提交到两个不同的域:firstwebsite.com和secondwebsite.com。如果它们在不同的域中,则需要对此进行特殊设置。

您可以阅读更多相关内容或查看此政策的说明。