在这个问题上花了几个小时,但找不到好的解决方案,所以这里是:
我在 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>
关于javascript - 按同一按钮触发 iframe 并提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488668/