触发iframe并在同一按钮上提交表单

Fire iframe and submit form on the same button press

本文关键字:按钮 提交 表单 iframe 触发      更新时间:2023-09-26

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

我在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‌​>

from testframe .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>