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

时间:2013-03-13 03:05:01

标签: javascript iframe cross-domain

我有一种情况,我希望同时将表单数据发布到2个不同的位置。我无法控制位置,它们是跨域的。 我在这里发现了一个上一篇文章,使用了iframe,我现在找不到,我已经合并了。它每次都提交给第一个,但第二个只提交25%的时间。我需要它在所有主流浏览器中更可靠地工作。尝试使用ajax但无法让它在IE中尝试跨域工作尝试在此论坛中提出的许多解决方案。 谢谢。 编

<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>    

1 个答案:

答案 0 :(得分:1)

在提交时复制表单并将表单提交给具有不同目的地的两个iframe,或使用AJAX。我强烈建议使用JQuery之类的框架,这样您就不必担心兼容性问题了。

您的代码发生了什么,它会尝试在提交第一页的过程中提交到第二页。如果第一页的提交在提交到第二页之前完成,则第二次提交将不会成功。如果您离开页面,当前页面中的所有脚本都将停止(因为您将访问www.firstwebsite.com)。

你可以在这里做的一个解决方案是:

  1. 更改submit2nd(),以便提交第一个和第二个网站。
  2. submit2nd()应该返回false,因此它不会尝试提交到action属性中的页面。
  3. 提交(点击提交按钮)后,复制表格。
  4. 第一种形式 - &gt;将action更改为www.firstwebsite.com - &gt;提交。
  5. 第二种形式 - &gt;将action更改为www.secondwebsite.com - &gt;提交。
  6. 注意:如果您希望使用AJAX,请确保您不会遇到跨域问题。在您的示例中,您尝试将表单提交到两个不同的域:firstwebsite.com和secondwebsite.com。如果它们位于不同的域上,则需要对此进行特殊设置。您可以read more对此进行检查,或查看此政策的explanation