【问题标题】:Fire iframe and submit form on the same button press在同一个按钮按下时触发 iframe 并提交表单
【发布时间】:2023-03-20 22:52:01
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery html forms iframe


    【解决方案1】:

    注意type="button" 是强制不提交表单

    如果页面和 iframe 代码来自同一个域,则可以直接返回

    &lt;script&gt;parent.document.getElementById("options-go-to-insure‌​r").submit()&lt;/script‌​&gt;

    来自 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>

    【讨论】:

    • 感谢您的回复!我现在就去检查!请注意,在按下按钮之前 iframe 无法触发 - 我认为您的代码与我的代码一样吗?
    • 查看我的更新,因为您修复了代码示例以显示 html
    • 嘿,除了#tracker 的来源之外,我想我得到了大部分内容?
    • 像魅力一样工作!非常感谢您的帮助!现在会仔细研究它,以确保我明白我做错了什么!再次感谢!
    • 您在将源分配给 iFrame 后立即调用了提交。它不会在执行回调之前等待 iFrame 加载
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多