点击iframe并在同一个按钮上提交表单

时间:2016-11-08 13:52:24

标签: 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>

1 个答案:

答案 0 :(得分:1)

请注意,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>