javascript - 按同一按钮触发 iframe 并提交表单

标签 javascript jquery html forms iframe

在这个问题上花了几个小时,但找不到好的解决方案,所以这里是:

我在 iframe 中有一个跟踪像素。单击按钮时,我想首先触发跟踪像素,然后提交表单。通常我会在中间有一个页面,在其中触发像素并传递表单,但在这个项目中我无法访问后端,也无法创建中间页面。我尝试简单地将 onClick='firePixel()' 添加到按钮,假设它将提交表单并加载 iframe,但事实并非如此。我还尝试创建第二个函数并以某种方式添加回调:onClick(firePixel(submitForm)) 将submitForm 作为回调 - 也没有运气。

P.S 我还尝试过在表单外部(如下所示)以及表单内部设置按钮 - 没有成功。

不确定这里的最佳实践是什么?我不介意 iframe 是否在后台触发 - 用户永远不会看到它 - 它只是一个跟踪像素。

请查找下面的代码(不起作用):

 <iframe id='conversioniFrame' data-src="testFrame.html" 
         src="about:blank" width='100px' height="100px">
<div class='panel clearfix'>
    <form id="options-go-to-insurer" action="/life/buy/" method="post">
        <!-- Form stuff -->
    </form>
    <button id="conversionButton" class="button primary expand apply-button" onclick="conversionFunction(submitForm())"><b>Apply Now</b></button>
</div>


<!-- STOP -->
<script>

function conversionFunction(callback) {
    var iframe = $("#conversioniFrame");
    iframe.attr("src", iframe.data("src"));
    callback();
}

function submitForm() {
    document.getElementById("options-go-to-insurer").submit();
}
</script>

最佳答案

请注意type="button"必须不提交表格

如果页面和 iframe 代码来自同一域,则只需返回

<script>parent.document.getElementById("options-go-to-insure‌​r").submit()</script‌​>

来自 testIframe.html

如果没有,试试这个

$(function() {
  $("#conversionButton").on("click", function() { // when button is clicked
    var $tracker = $("#conversioniFrame");
    $tracker.attr("src", $tracker.data("src")); // load the page
  });
  $("#conversioniFrame").on("load", function() { // when page has loaded
    $("#options-go-to-insurer").submit(); // submit the form
  });
});
<iframe id='conversioniFrame' data-src="testFrame.html" src="about:blank" width='100px' height="100px">
  <div class='panel clearfix'>
    <form id="options-go-to-insurer" action="/life/buy/" method="post">
      <!-- Form stuff -->
    </form>
    <button type="button" id="conversionButton" class="button primary expand apply-button"><b>Apply Now</b>
    </button>
  </div>

关于javascript - 按同一按钮触发 iframe 并提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488668/

相关文章:

html - 当所有内容都适合页面时,我的网站似乎可以滚动

javascript - 具有当前表单值的 innerHTML

javascript - 如何在js中创建 TreeView

javascript - JQuery-Mobile滚动条

jquery - 在 Rails 中使用 PJax 加载 Doc Ready 上的所有 jQuery 变量

javascript - 在 javascript/jquery 中重新映射按键

html - 裁剪边界半径非常大的图像

javascript - 在 Controller 渲染 View 之前将ajax数据加载到$scope中

javascript - 如何在随机存储到另一个数组后找到与哪个数组相关的值(例如 :array a, 数组 b)

jQuery 移动覆盖主题半透明?