在这上面花了好几个小时,却找不到一个好的解决方案,所以可以这样:
我在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-insurer").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>